Basic Calculator in C++
Build a four-operation calculator in C++ with switch on a char operator. Covers break and fall-through, division by zero, and reporting errors with return 1.
1#include <iostream>2using namespace std;34int main() {5 char op;6 double num1, num2, result;78 cout << "Enter operator (+, -, *, /): ";9 cin >> op;1011 cout << "Enter two numbers: ";12 cin >> num1 >> num2;1314 switch(op) {15 case '+':16 result = num1 + num2;17 break;18 case '-':19 result = num1 - num2;20 break;21 case '*':22 result = num1 * num2;23 break;24 case '/':25 if (num2 != 0) {26 result = num1 / num2;27 } else {28 cout << "Error: Division by zero!" << endl;29 return 1;30 }31 break;32 default:33 cout << "Error: Invalid operator!" << endl;34 return 1;35 }3637 cout << num1 << " " << op << " " << num2 << " = " << result << endl;3839 return 0;40}
Sample Output
5 * 4 = 20
The case for * ran and the result was printed.
In this one
- How switch picks a case by character
- Why each case needs break
- How to guard division by zero
- What return 1 means as an exit code
How it works
- 1
Read the operator (*).
- 2
Read two numbers (5 and 4).
- 3
switch jumps to case '*' and computes 20.
- 4
break leaves the switch.
- 5
Print 5 * 4 = 20.
Edge cases
Division by zero
Enter / then 7 0.
The guard prints Error: Division by zero! and returns 1 before dividing.
Unknown operator
Enter %.
No case matches, so default prints Error: Invalid operator! and returns 1.
What's going on
A tiny C++ calculator: one operator, two numbers, switch. Sample * 5 4 → 5 * 4 = 20.
char op;
double num1, num2, result;
double so 7 / 2 is 3.5, not 3.
cin >> op;
cin >> num1 >> num2;
switch(op) picks a branch by the character.
case '+': add, break;
case '-': subtract, break;
case '*': multiply, break;
case '/': if num2 != 0 divide, else print Error: Division by zero! and return 1.
default: invalid operator, return 1.
Forget break and + falls into - (switch fall-through). That's the bug this program exists to teach.
^ is not power. Type ^ and you hit default.
After a successful case, print num1 op num2 = result.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which types can a C++ switch test?
Pick an answer to check it.
Question 2
What does return 1 from main usually signal?
Pick an answer to check it.
Questions people ask
What happens if I forget break?
Execution falls into the next case. After + it would also do -, overwriting the result.
Why is the result double?
So 7 / 2 gives 3.5 instead of the integer 3.
Can switch use strings?
No. switch works on integer-like types such as int, char, and enums.