switch Calculator
Completed
Read a op b where op is one of + - * /. Print the result (integer division), division by zero, or unknown operator, using switch.
Input
One line: integer, operator, integer.
Output
One line.
Example
Input
6 * 7
Output
42
Editor
C
Hints
switch on a char uses case '+':
Don't forget break, or execution falls into the next case.
Solution explanation
switch compares one value against constant cases; default catches the rest.
Show solution
#include <stdio.h>
int main() {
int a, b;
char op;
scanf("%d %c %d", &a, &op, &b);
switch (op) {
case '+':
printf("%d\n", a + b);
break;
case '-':
printf("%d\n", a - b);
break;
case '*':
printf("%d\n", a * b);
break;
case '/':
if (b == 0) {
printf("division by zero\n");
} else {
printf("%d\n", a / b);
}
break;
default:
printf("unknown operator\n");
}
return 0;
}