Basic Calculator

Program to create a basic calculator with arithmetic operations

BeginnerTopic: Loop Programs
Back

C++ Basic Calculator Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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;
}
Output
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:

Takes an arithmetic operator (+, -, *, /) as input
Takes two numbers as input
Performs the corresponding arithmetic operation
Displays the result
Handles errors (division by zero, invalid operator)

This is a fundamental program that teaches:

Switch statement for multiple conditions
Character input handling
Error handling and validation
Basic arithmetic operations

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring Variables

char op;

double num1, num2, result;

Variable `op`:

Stores the arithmetic operator (+, -, *, /)
char type is perfect for single character operators

Variable `num1` and `num2`:

Store the two numbers for calculation

-

`double` type

allows decimal numbers

Why use `double` instead of `int`?

Users might want to calculate with decimals
Example: 5.5 + 2.3 = 7.8
Division often produces decimal results: 7 / 2 = 3.5
double handles both integers and decimals

Variable `result`:

Stores the result of the calculation
Also double to handle decimal results

---

4. Taking Input From User

`cout << "Enter operator (+, -, *, /): ";`

cin >> op;

`cout << "Enter two numbers: ";`

cin >> num1 >> num2;

Step 1: Get operator

Prompts user to enter an operator
Reads single character: +, -, *, or /

Step 2: Get numbers

Prompts user to enter two numbers
Reads both numbers in one line

Example:

User enters: operator =

*, 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 value1

Why use switch instead of if-else?

Cleaner and more readable for multiple conditions
More efficient (compiler can optimize)
Easier to add new operations

---

6. Addition Case

`case '+': `

result = num1 + num2;

break;

What happens:

If op == '+', execute this block
Calculate: result = num1 + num2
break; exits the switch (prevents falling through to next case)

Example:

op = '+', num1 = 5, num2 = 4
result = 5 + 4 = 9

---

7. Subtraction Case

`case '-': `

result = num1 - num2;

break;

Example:

op = '-', num1 = 10, num2 = 3
result = 10 - 3 = 7

---

8. Multiplication Case

`case '*': `

result = num1 * num2;

break;

Example:

op = '*', num1 = 5, num2 = 4
result = 5 * 4 = 20

---

9. Division Case with Error Handling

`case '/': `

if (num2 != 0)

result = num1 / num2;

else

` cout << "Error: Division by zero!" << endl;`

return 1;

break;

Why check for zero?

Division by zero is undefined in mathematics
Causes program crash or undefined behavior
We must handle this error gracefully

What happens:

If num2 ≠ 0:

Perform division: result = num1 / num2
Example: 10 / 2 = 5.0

If num2 = 0:

Print error message: "Error: Division by zero!"
return 1; exits program with error code
Prevents crash and informs user

Example:

num1 = 10, num2 = 0
Output:

"Error: Division by zero!"

Program exits safely

---

10. Default Case - Invalid Operator

`default: `
` cout << "Error: Invalid operator!" << endl;`

return 1;

When does this execute?

If op doesn't match any case (+, -, *, /)
Examples: user enters '&', '%', 'x', etc.

What happens:

Print error message
Exit program with error code

Example:

User enters operator:

'%'

Output:

"Error: Invalid operator!"

---

11. The break Statement

Why `break;` is crucial:

Without break;, execution "falls through" to next case
This would execute multiple cases unintentionally

Example without break:

case '+':

result = num1 + num2;

case '-':

result = num1 - num2;

If op = '+', it would do both addition AND subtraction! ❌
    // Missing break!

With break:

Execution stops after matching case
Only the correct operation is performed ✅

---

12. Displaying the Result

cout << num1 << " " << op << " " << num2 << " = " << result << endl;

This prints:

First number: 5
Space
Operator: *
Space
Second number: 4
Text: " = "
Result: 20
New line

Output:

5 * 4 = 20

---

13. Complete Example Walkthrough

Example 1: Multiplication

Input:

Operator:

*

Numbers:

5, 4

Execution:

op = '*' → matches case '*':
result = 5 * 4 = 20
break; → exit switch
Display:

"5 * 4 = 20"

Example 2: Division by Zero

Input:

Operator:

/

Numbers:

10, 0

Execution:

op = '/' → matches case '/':
Check: num2 == 0

true

Print:

"Error: Division by zero!"

return 1; → program exits

Example 3: Invalid Operator

Input:

Operator:

%

Numbers:

5, 4

Execution:

op = '%' → doesn't match any case
Executes default: case
Print:

"Error: Invalid operator!"

return 1; → program exits

---

14. Return Values

`return 0;` (success):

Normal exit after successful calculation
Indicates program completed successfully

`return 1;` (error):

Exit when error occurs (division by zero, invalid operator)
Indicates program ended due to error
Useful for error handling and debugging

---

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

Switch statement handles multiple cases based on operator
Each case performs corresponding arithmetic operation
break; prevents falling through to next case
Error handling for division by zero and invalid operators
double type allows decimal number calculations
return 1; indicates error, return 0; indicates success

This program teaches:

Switch statement for multiple conditions
Character input handling
Error handling and validation
Arithmetic operations in programming
Program exit codes

Understanding this calculator helps in:

Building more complex calculators
Menu-driven programs
Error handling patterns
User input validation

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.

Table of Contents