+92 332 4229 857 99ProjectIdeas@Gmail.com

Switch example (C++)


Switch example
Switch allows selection among multiple sections of the code depending on the value in the switch statement.
Same thing can be done by using If-else-if statement:

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

Code

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

using namespace std;

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;
          
              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;
              }
          
            _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: