In C program
Write a program that mimics a calculator.
The program should prompt for two integers and the operation to be performed.
It should then output the numbers, the operator, and the result. All the results should also be integers. For division, if the denominator is zero, output an appropriate message.
Example (Numbers and symbols with underscore indicate an input):
Enter integer +|-|*|/ integer: 3 + 2 3 + 2 = 5 -------------------------------------------- Enter integer +|-|*|/ integer: 13 * 5 13 * 5 = 65 -------------------------------------------- Enter integer +|-|*|/ integer: 5 / 0 5 / 0 = ERROR Cannot divide by zero
HINT: This might be a good place to use a switch statement!
#include <stdio.h> int main() { int n1, n2, result; char ch; printf("Enter integer +|-|*|/ integer: "); scanf("%d %c %d", &n1, &ch, &n2); printf("\n"); switch (ch) { case '+': result = n1 + n2; break; case '-': result = n1 - n2; break; case '*': result = n1 * n2; break; case '/': if (n2 == 0) { printf("%d / 0 = ERROR\n" "Cannot divide by zero\n", n1); return 1; } result = n1 / n2; break; default: printf("Error. Invalid operator\n"); return 1; } printf("%d %c %d = %d\n", n1, ch, n2, result); return 0; }
Get Answers For Free
Most questions answered within 1 hours.