Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C calculator program In the following C code given below the main method is alre

ID: 3700033 • Letter: C

Question

C calculator program

In the following C code given below the main method is already written for you. The main method reads from standard input an expression of the following form:

<operand> <operator> <operand>

There is also a function called doMath which takes two integer arguments and a character argument and returns an integer value. The first two arguments are the operands collected from input in the same order as they appear. The last character argument is the ASCII representation of the math operator from input.

Your job is to finish the doMath function so that it supports the following operation

Addition (+)

·         Subtraction (-)

·         Multiplication (*)

·         Division (/)

·         Remainder (%)

·         XOR (^)

·         Bitwise AND (&)

·         Bitwise OR (|)

The function should return the mathematical result of the operation on the two operands.

Use a switch statement. This function can and should be done without the use of if statements. The default case is that the doMath function print an error message and then should call the function exit(EXIT_FAILURE).The exit function allows the program to terminate immediately from any point in the code and the argument to it is a status code

Please write the code where it says "write your code here "

Code


#include <stdio.h>

int doMath(int left, int right, char oper) {
   /* write your code here */
}

void main() {
    int left, right;
    char oper;
    if (scanf("%d %c %d", &left, &oper, &right) == 3)
        printf("%d %c %d = %d ", left, oper, right, doMath(left, right, oper));
    else
        printf("Bad Input Format ");
}

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
int doMath(int left, int right, char oper) {
/* write your code here */
int result;
switch(oper) {
case '+': result = left + right; break;
case '-': result = left - right; break;
case '*': result = left * right; break;
case '/':
if(right == 0) {
printf("Denominator can not be zero ");
result= -1;
} else {
result = left /(double) right;
}
break;
case '%': result = left % right; break;
case '^': result = left ^ right; break;
case '&': result = left & right; break;
case '|': result = left | right; break;
default:
printf("Invalid operator ");
exit(EXIT_FAILURE);
}
return result;
}

void main() {
int left, right;
char oper;
if (scanf("%d %c %d", &left, &oper, &right) == 3)
printf("%d %c %d = %d ", left, oper, right, doMath(left, right, oper));
else
printf("Bad Input Format ");
}

Output: