Google News
logo
C++ Program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case
In the following example of C++ program that implements a simple calculator using switch...case statement to perform addition, subtraction, multiplication, and division :
Program :
#include <iostream>

using namespace std;

int main() {
    char operation;
    double num1, num2;

    cout << "Enter the operator (+, -, *, /): ";
    cin >> operation;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    switch (operation) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;

        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;

        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;

        case '/':
            if (num2 == 0) {
                cout << "Error: division by zero";
            } else {
                cout << num1 << " / " << num2 << " = " << num1 / num2;
            }
            break;

        default:
            cout << "Error: invalid operator";
            break;
    }

    return 0;
}
Output :
Enter the operator (+, -, *, /): *
Enter two numbers: 2.3 4.7
2.3 * 4.7 = 10.81
The program prompts the user to enter an operator (+, -, *, or /) and two numbers. It then uses a switch...case statement to perform the appropriate arithmetic operation based on the operator entered.

If the user enters an invalid operator, the program outputs an error message. If the user attempts to divide by zero, the program also outputs an error message.