C++ Program to Make a Simple Calculator

18/04/2024 0 By indiafreenotes

Creating a Simple Calculator in C++ involves handling basic arithmetic operations like addition, subtraction, multiplication, and division. This calculator will take an operation selection input from the user, prompt for two numbers, perform the selected operation, and display the result. To make the calculator user-friendly, we can use a loop that allows users to perform multiple calculations without restarting the program.

Here’s a simple implementation of such a calculator:

#include <iostream>

using namespace std;

int main() {

    char operation;

    double num1, num2;

    // Loop to allow multiple operations

    while (true) {

        cout << “Enter an operation (+, -, *, /) or Q to quit: “;

        cin >> operation;

        if (operation == ‘Q’ || operation == ‘q’) {

            cout << “Calculator exited.” << endl;

            break;

        }

        cout << “Enter the first number: “;

        cin >> num1;

        cout << “Enter the second number: “;

        cin >> num2;

        switch (operation) {

            case ‘+’:

                cout << num1 << ” + ” << num2 << ” = ” << num1 + num2 << endl;

                break;

            case ‘-‘:

                cout << num1 << ” – ” << num2 << ” = ” << num1 – num2 << endl;

                break;

            case ‘*’:

                cout << num1 << ” * ” << num2 << ” = ” << num1 * num2 << endl;

                break;

            case ‘/’:

                if (num2 != 0.0)

                    cout << num1 << ” / ” << num2 << ” = ” << num1 / num2 << endl;

                else

                    cout << “Division by zero error!” << endl;

                break;

            default:

                cout << “Invalid operation!” << endl;

        }

    }

    return 0;

}

This program starts with a loop that continuously prompts the user to enter an operation. If the user inputs ‘Q’ or ‘q’, the program exits. For any other operation, it asks for two numbers. Using a switch statement, it then performs the operation corresponding to the user’s choice. After displaying the result, the loop restarts, allowing another operation to be selected and performed without restarting the program.

Key Features of This Program:

  • Modularity and Readability:

The use of a switch statement makes it easy to understand and modify the code to add more operations if needed.

  • Error Handling for Division:

There’s a check to prevent division by zero, which is a common runtime error in division operations.

  • Loop for Continuous Operation:

The loop allows the calculator to be used multiple times without needing to be restarted, enhancing user experience.

  • User Input Validation:

The program includes a basic form of user input validation for the operation. It ensures that if an invalid operation is entered, an error message is displayed, and no unnecessary calculations are attempted.