C++ Program to Implement a Simple Calculator (Add, Subtract, Multiply, Divide)

1. Introduction

Calculators are fundamental tools that can be found virtually everywhere, from our smartphones to standalone devices. Have you ever wondered how to build a simple one using C++? This blog post will guide you through the process of creating a basic calculator that can add, subtract, multiply, and divide.

2. Program Overview

Our calculator will:

1. Prompt the user to input two numbers.

2. Ask the user to select an operation (add, subtract, multiply, or divide).

3. Perform the selected operation and display the result.

3. Code Program

#include<iostream>
using namespace std;

int main() {
    // Declare variables for the two numbers, the result of the operation, and the operation itself
    double num1, num2, result;
    char operation;

    // Prompt user to input the first number
    cout << "Enter first number: ";
    cin >> num1;

    // Prompt user to input the second number
    cout << "Enter second number: ";
    cin >> num2;

    // Prompt user to specify the desired arithmetic operation
    cout << "Enter operation (+, -, *, /): ";
    cin >> operation;

    // Use a switch-case construct to determine the operation and calculate the result
    switch(operation) {
        case '+':
            // Addition
            result = num1 + num2;
            break;
        case '-':
            // Subtraction
            result = num1 - num2;
            break;
        case '*':
            // Multiplication
            result = num1 * num2;
            break;
        case '/':
            // Division
            if(num2 != 0) { // Ensure denominator is not zero
                result = num1 / num2;
            } else {
                // Division by zero is undefined, hence display an error message
                cout << "Division by zero is not allowed!";
                return 1; // Return with an error code
            }
            break;
        default:
            // Inform the user if they entered an invalid operation
            cout << "Invalid operation!";
            return 1; // Return with an error code
    }

    // Display the result of the operation
    cout << "Result: " << result << endl;

    return 0; // Successful completion of program
}

Output:

Enter first number: 5
Enter second number: 3
Enter operation (+, -, *, /): +
Result: 8

4. Step By Step Explanation

1. We use cin to get two numbers and an operation symbol from the user.

2. Using a switch statement, we branch to the appropriate arithmetic operation based on the symbol entered.

3. If the division operation is chosen and the second number is 0, we display an error message as dividing by zero is undefined in mathematics.

4. If a valid operation is chosen, the calculator displays the result. If not, an error message is shown.

Comments