In: Computer Science
Write a program, which will act as a simple four-function calculator. That is, it will read a number, read an operator, read another number, then do the operation. The calculator works with integers and uses four functions: +, -, *, and /. After the first operation is completed, the program will read another operator and uses the result of the previous operation as the first value for the next operation. If the user enters either an upper- or lower-case C the result is cleared and then the user starts entering a new number. If the user enters an X, the calculator is turned off. The various input values (i.e. numbers, operators, commands) will be followed by the ENTER key. Your program should prompt the user on what the user is to do. The commands C and X may be entered in place of an operator.
NOTES:
The person using the calculator has a terrible time using a keyboard and may not always enter a valid operator. If this happens the program should ask for another operator. Regardless of the math operation attempted, the program must not die. If the math operation would cause a fatal error in your program you should check for it and issue an error message rather than attempting the operation.
Please write the code for C programming, not C++ or Java
SimpleCalculator.c
#include<stdio.h>
int main()
{
// variables declaration
char operator;
int operand1=0,operand2=0,result=0;
printf("\n **** SIMPLE CALCULATOR ****\n\n");
while(1)
{
printf("****************************\n");
printf("Enter operand 1: ");
scanf("%d",&operand1); // get
first operand
op:
printf("Enter an operator:
");
scanf("%s",&operator); // get
an operator
// check operator is instructing to
clear or not
if(operator=='c' ||
operator=='C')
{
operand1=operand2=0;
printf("Cleared...!!!\n****************************\n");
continue;
}
else
// check operator is instructing to
turn off calculator or not
if(operator=='x' ||
operator=='X')
{
break;
}
else
// check operator is valid or
not
if(operator!='+' &&
operator!='-' && operator!='*' &&
operator!='/')
{
printf("Wrong
operator. please enter again...!!!\n");
goto op; // jump
to op
}
else
{
op2:
printf("Enter
operand 2: ");
scanf("%d",&operand2); // get second operand
//
addition
if(operator=='+')
{
result=operand1+operand2;
}
else
//
subtraction
if(operator=='-')
{
result=operand1-operand2;
}
else
//
multiplication
if(operator=='*')
{
result=operand1*operand2;
}
else
//
division
if(operator=='/')
{
// check operand 2 is 0 or not
// in the case of division only
if(operand2==0)
{
printf("Can not divide by
zero...!!!\n");
goto op2; // jump to
op2
}
result=operand1/operand2;
}
operand1=result;
// print
result
printf("Result=
%d\n",result);
goto op; // jump
to op
}
}
printf("\n******* DONE *******");
return 0;
}
Output
