Basic Calculator
Program to create a basic calculator with arithmetic operations
C++ Basic Calculator Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
char op;
double num1, num2, result;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
switch(op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error: Division by zero!" << endl;
return 1;
}
break;
default:
cout << "Error: Invalid operator!" << endl;
return 1;
}
cout << num1 << " " << op << " " << num2 << " = " << result << endl;
return 0;
}Enter operator (+, -, *, /): * Enter two numbers: 5 4 5 * 4 = 20
Understanding Basic Calculator
This program creates a basic calculator that performs arithmetic operations (addition, subtraction, multiplication, division) on two numbers. It demonstrates the switch statement, which is perfect for handling multiple cases based on a single value. The program also includes error handling for division by zero and invalid operators.
---
1. What This Program Does
The program:
This is a fundamental program that teaches:
---
2. Header File: #include <iostream>
#include <iostream>
Provides:
cout → for displaying outputcin → for reading input---
3. Declaring Variables
char op;
double num1, num2, result;
Variable `op`:
char type is perfect for single character operatorsVariable `num1` and `num2`:
-
`double` type
Why use `double` instead of `int`?
double handles both integers and decimalsVariable `result`:
double to handle decimal results---
4. Taking Input From User
cin >> op;
cin >> num1 >> num2;
Step 1: Get operator
Step 2: Get numbers
Example:
*, num1 =
5
, num2 =
4
op = '*', num1 = 5.0, num2 = 4.0---
5. Understanding the Switch Statement
switch(op)
The switch statement is perfect for handling multiple cases based on a single value.
Syntax:
switch (variable) {
case value1:
break;
case value2:
// code for value2
break;
default:
// code if no case matches
}
// code for value1Why use switch instead of if-else?
---
6. Addition Case
result = num1 + num2;
break;
What happens:
op == '+', execute this blockresult = num1 + num2break; exits the switch (prevents falling through to next case)Example:
op = '+', num1 = 5, num2 = 4result = 5 + 4 = 9---
7. Subtraction Case
result = num1 - num2;
break;
Example:
op = '-', num1 = 10, num2 = 3result = 10 - 3 = 7---
8. Multiplication Case
result = num1 * num2;
break;
Example:
op = '*', num1 = 5, num2 = 4result = 5 * 4 = 20---
9. Division Case with Error Handling
if (num2 != 0)
result = num1 / num2;
else
return 1;
break;
Why check for zero?
What happens:
If num2 ≠ 0:
result = num1 / num2If num2 = 0:
return 1; exits program with error codeExample:
num1 = 10, num2 = 0"Error: Division by zero!"
---
10. Default Case - Invalid Operator
return 1;
When does this execute?
op doesn't match any case (+, -, *, /)What happens:
Example:
'%'
"Error: Invalid operator!"
---
11. The break Statement
Why `break;` is crucial:
break;, execution "falls through" to next caseExample without break:
case '+':
result = num1 + num2;
case '-':
result = num1 - num2;
op = '+', it would do both addition AND subtraction! ❌ // Missing break!With break:
---
12. Displaying the Result
cout << num1 << " " << op << " " << num2 << " = " << result << endl;
This prints:
Output:
5 * 4 = 20
---
13. Complete Example Walkthrough
Example 1: Multiplication
Input:
*
5, 4
Execution:
op = '*' → matches case '*':result = 5 * 4 = 20break; → exit switch"5 * 4 = 20"
Example 2: Division by Zero
Input:
/
10, 0
Execution:
op = '/' → matches case '/':num2 == 0 →true
"Error: Division by zero!"
return 1; → program exitsExample 3: Invalid Operator
Input:
%
5, 4
Execution:
op = '%' → doesn't match any casedefault: case"Error: Invalid operator!"
return 1; → program exits---
14. Return Values
`return 0;` (success):
`return 1;` (error):
---
15. Extending the Calculator
You can easily add more operations:
case '%':
result = (int)num1 % (int)num2; // Modulo
break;
case '^':
result = pow(num1, num2); // Power
break;
---
Summary
break; prevents falling through to next casedouble type allows decimal number calculationsreturn 1; indicates error, return 0; indicates successThis program teaches:
Understanding this calculator helps in:
This is a fundamental program that demonstrates practical programming concepts used in many real-world applications. The switch statement pattern is especially useful for handling multiple options in user interfaces and menu systems.
Let us now understand every line and the components of the above program.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.
Practical Learning Notes for Basic Calculator
This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.