in ,

C++ Calculator Using Switch Case

c++-calculator

Today We Will Create a simple calculator. To addition, multiply, subtract, and divide using the switch and break statements in c++.

In this program, we tack arithmetic operation((+, *, -, /). And we will get two inputs from the user and perform the calculator operation according to user input values.

After that we will use switch case in this program and we try to make program is easy. So Let’s make program of C++ Calculator.

#include <iostream>
using namespace std;
int main() 
{
    char operation;
    float val1, val2;
    cout << "Enter operator: +, *, -, /: ";
    cin >> operation;

    cout << "Enter two operands: ";
    cin >> val1 >> val2;

    switch(operation) {
        case '+':
            cout << val1 << " + " << val2 << " = " << val1 + val2;
            break;

        case '*':
            cout << val1 << " * " << val2 << " = " << val1 * val2;
            break;

	case '-':
            cout << val1 << " - " << val2 << " = " << val1 - val2;
            break;

        case '/':
            cout << val1 << " / " << val2 << " = " << val1 / val2;
            break;

        default:
            cout << "Error! operator is not correct";
            break;
    }
      return 0;
}

OUTPUT:-

c++-calculator

The operator operators are store in the variable operation and the two operators are store in Val1 and Val2, respectively.

After that, the switch … case statement is use to check the operator enter by the user.

If the user enters +, the statements for the case: ‘+‘ are execute and the program ends.

If the user enters – then, the statements for the case: ‘-‘ are execute and the program ends.

This program works similarly for * and / operator operators. However, if the operator does not match any four-letter [+, -, * and /], a default statement is execute that displays an error message in c++ Calculator.

RUN CODE ONLINE:-

Leave a Reply

Your email address will not be published. Required fields are marked *

red-dead-redemption-2-crashing

Red Dead Redemption 2 crashing: How To Solve

python-absolute-value

Python Absolute Value