+92 332 4229 857 99ProjectIdeas@Gmail.com

Switch example with function (C++)


Switch example with function
Switch allows selection among multiple sections of the code depending on the value in the switch statement.
switchFunction() takes 3 parameters:
num1 takes the first number.
num2 takes the second number.
operation takes the operation to be performed on both numbers.

Following code demonstrates basic operations on 2 integer values using switch statement.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

void switchFunction(double num1,double num2,char operation)
{
            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 '/':{cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;break;}
             case 'A':
                     {
                      cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;
                      cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;
                      cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;
                      cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;
                      break;
                     }
              default:
                     cerr<<"NOT A VALID OPERATION"<<endl;
            }
}

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

            cout<<"ENTER FIRST NUMBER  > ";
            cin>>num1;

            cout<<"ENTER SECOND NUMBER > ";
            cin>>num2;
          
            cout<<"ENTER OPERATION"<<endl;
            cout<<"+ FOR ADDITION"<<endl;
            cout<<"- FOR ADDITION"<<endl;
            cout<<"* FOR ADDITION"<<endl;
            cout<<"/ FOR ADDITION"<<endl;
            cout<<"A FOR ADDITION"<<endl;
            cin>>operation;

            switchFunction(num1,num2,operation);
          
            _getche();
            return 0;
}
Output
ENTER FIRST NUMBER  > 6
ENTER SECOND NUMBER > 5
ENTER OPERATION
+ FOR ADDITION
- FOR ADDITION
* FOR ADDITION
/ FOR ADDITION
A FOR ADDITION
A
6 + 5 = 11
6 - 5 = 1
6 * 5 = 30
6 / 5 = 1.2

Also visit related articles

0 comments: