C Project: Simple Calculator
A simple calculator puts switch, functions, and input together. It reads an operator and two numbers, then works out the answer.
Add with a switch
An operator and two numbers are read, then the switch picks the + case. With 12 and 4, the output is 16.00.
#include <stdio.h>
int main() {
char op = ' ';
double a = 0.0;
double b = 0.0;
printf("Enter an operator and two numbers.\n");
scanf(" %c %lf %lf", &op, &a, &b);
switch (op) {
case '+':
printf("%.2f + %.2f = %.2f\n", a, b, a + b);
break;
default:
printf("Unknown operator.\n");
break;
}
return 0;
}Divide, with a zero check
The second number is checked before dividing. With 10 and 0, the output is a plain message instead of a division.
#include <stdio.h>
int main() {
char op = ' ';
double a = 0.0;
double b = 0.0;
printf("Enter an operator and two numbers.\n");
scanf(" %c %lf %lf", &op, &a, &b);
switch (op) {
case '/':
if (b == 0.0) {
printf("Cannot divide by zero.\n");
} else {
printf("%.2f / %.2f = %.2f\n", a, b, a / b);
}
break;
default:
printf("Unknown operator.\n");
break;
}
return 0;
}Small functions do the maths
add and multiply each do one calculation. Called with 6.0 and 3.0, they give 9.00 and 18.00.
#include <stdio.h>
double add(double a, double b) {
return a + b;
}
double multiply(double a, double b) {
return a * b;
}
int main() {
printf("%.2f\n", add(6.0, 3.0));
printf("%.2f\n", multiply(6.0, 3.0));
return 0;
}Example
#include <stdio.h>
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
return a / b;
}
int main() {
char op = ' ';
double a = 0.0;
double b = 0.0;
printf("Enter an operator and two numbers.\n");
scanf(" %c %lf %lf", &op, &a, &b);
switch (op) {
case '+':
printf("%.2f + %.2f = %.2f\n", a, b, add(a, b));
break;
case '-':
printf("%.2f - %.2f = %.2f\n", a, b, subtract(a, b));
break;
case '*':
printf("%.2f * %.2f = %.2f\n", a, b, multiply(a, b));
break;
case '/':
if (b == 0.0) {
printf("Cannot divide by zero.\n");
} else {
printf("%.2f / %.2f = %.2f\n", a, b, divide(a, b));
}
break;
default:
printf("Unknown operator.\n");
break;
}
return 0;
}Key points
- scanf can read a character and two numbers in one line.
- A space before %c in scanf skips leftover whitespace.
- switch picks a case by the operator character.
- Each case calls a small function that does one calculation.
- add, subtract, multiply, and divide are four small functions.
- Division checks for zero before it divides.
- default runs when the operator is none of the four.
The program reads * and the numbers 6 and 3. The switch picks the * case, which calls multiply. The answer is 18.00.
Note
The operator is a char, so each case uses single quotes, like '+'.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the calculator print when you divide by zero?