• June 12, 2021

PHSARIT

Bring Technology Ideas with you

 Switch Case Statement for Simple Calculator in C++

The switch statement is one of the control statement that allows programmers to execute a block of code among many alternatives.

The syntax of the switch statement in C++ is:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;
    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

This is an example to use switch statement to calculate the two number variable base on the specific assigned operators

#include <iostream>

using namespace std;

int main()
{
   double num1,num2,result;
   char choice;
   cout<<"Please enter first number:";
   cin >>num1;
   cout<<"Please enter second number:";
   cin >>num2;
   cout<<"Please select your choice:";
   cin>>choice;
   switch(choice)
   {
       case '+':
            result = num1 + num2;
            break;

        case '-':
            result = num1 - num2;
            break;

        case '*':
            result = num1 * num2;
            break;

        case '/':
            result = num1 / num2;
            break;

        default:
            cout<<"Invalid operator";
    }
   cout<<"The result is:"<<result;

    return 0;
}

See the result:

    Related post