Patterns and small projects · intermediate
C Program to Make a Simple Calculator Using switch
Make a simple calculator in C with switch...case that reads expressions like "12 * 4" with scanf(), handles division by zero and unknown operators.
- switch...case
- scanf() with %c
- reading until end of input
- error handling
A calculator is the classic switch...case exercise: read two numbers and an operator, then choose the operation with a switch. This version reads one expression per line until the input ends, and reports bad input instead of crashing or printing garbage.
The program
#include <stdio.h>
int main(void) {
double a, b;
char op;
while (scanf("%lf %c %lf", &a, &op, &b) == 3) {
switch (op) {
case '+':
printf("%g + %g = %g\n", a, b, a + b);
break;
case '-':
printf("%g - %g = %g\n", a, b, a - b);
break;
case '*':
printf("%g * %g = %g\n", a, b, a * b);
break;
case '/':
if (b == 0)
printf("Error: cannot divide by zero\n");
else
printf("%g / %g = %g\n", a, b, a / b);
break;
default:
printf("Error: unknown operator %c\n", op);
}
}
return 0;
}12 * 4
7 / 2
5 / 0
3 ^ 212 * 4 = 48
7 / 2 = 3.5
Error: cannot divide by zero
Error: unknown operator ^How it works
- scanf("%lf %c %lf") reads a number, an operator character and another number; the spaces in the format skip any whitespace.
- The loop continues as long as scanf converts all three items, so it stops at the end of the input.
- switch (op) jumps to the matching case; break leaves the switch after each operation.
- Division checks for zero first. The default case reports any other operator.
- %g prints doubles without trailing zeros: 48 instead of 48.000000.
Another way: With a function per operation
Moving the work into a function that returns a status keeps main short and makes the calculator easy to test.
#include <stdio.h>
int calculate(double a, char op, double b, double *out) {
switch (op) {
case '+': *out = a + b; return 1;
case '-': *out = a - b; return 1;
case '*': *out = a * b; return 1;
case '/': if (b == 0) return 0; *out = a / b; return 1;
default: return 0;
}
}
int main(void) {
double r;
if (calculate(10, '-', 4, &r))
printf("%g\n", r);
if (!calculate(1, '/', 0, &r))
printf("invalid\n");
return 0;
}6
invalidCommon mistakes
- Writing scanf("%lf%c%lf") without the space before %c: %c then reads the space or newline instead of the operator.
- Forgetting break, so execution falls through into the next case and prints two results.
- Using int for the numbers, so 7 / 2 gives 3 (integer division).
Try it yourself
- Add % for integers and ^ for powers (with pow() from math.h).
- Keep a running total so a line can start with an operator.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.