Challenge: Tiny Calculator
Completed
Read a whole number, an operator (+ - * /) and another whole number, like 6 * 7, and print the result. For / use whole-number division. If the operator is / and the second number is 0, print Cannot divide by zero.
Input
A number, a space, an operator, a space, a number.
Output
The result, or the error message.
Example
Input
6 * 7
Output
42
Editor
C
Hints
scanf("%d %c %d", &a, &op, &b) reads all three parts.
A switch on op is a neat fit.
Check b == 0 before dividing.
Solution explanation
The switch picks the right calculation; inside the / case an if protects us from dividing by zero.
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("Cannot divide by zero\n");
} else {
printf("%d\n", a / b);
}
break;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module