In: Computer Science
Use a switch statement on a char variable to write a function that's a simple calculator that keeps running waiting for input
Should have a do while loop that continually loops the function, prompting for a new input and new operator, until the calculator returns 0, in which case it will close.
As the programming language is not mentioned, it is done C language
Source Code:
#include<stdio.h> // header file for input output
functions
main() { // main function
int s,total; // declaring required variables
char cha;
do{ // do while starting
printf(" Enter a number: "); //
asking for a number
scanf("%d",&s); // storing it
into s every time
printf(" Enter a operator(+,-,*,/):
"); // asking for a operator
scanf(" %c",&cha); // stroring
into cha variable
switch(cha){ // switch statement
testing the operator
case '+':
total+=s; // if operator is + then add s to previous total
break;
case '-':
total-=s; // if - substract sfrom total
break;
case '*':
total*=s; // if * multiply s with total
break;
case '/':
total/=s;// if / divide s by total
break;
default:
printf(" Enter a valid operator!!");
}
printf(" Total is: %d ",total); //
priting the total in each round
}while(total!=0); // until total becomes 0
}// end of main
OUTPUT:
The below image is the output of the above code. It is run until the value becomes 0.