Ads 468x60px

Wednesday, 2 January 2013

Switch

Multiple if can be very complex if there are a lots of conditions and for menu driven programs if else will be very complex, in these type of conditions using switch is very good idea it will reduce the complexity of the program.

Syntax
switch (expression)
{
   case 1:
      statements; break;
   case 2:
      statements; break;
   .
   .
   case n:
      statements; break;
   default:
      statements; break;
}

Example
Write a program that will add, subtract, divide and multiply two integers according to user's choice.
#include<iostream.h>
#include<conio.h>

void main()
{
  int a,b,r,choice;
  cout<<"Enter two numbers\n";
  cin>>a>>b;
  cout<<"Enter your choice\n";
  cout<<"1. Add"<<endl;
  cout<<"2. Subtract"<<endl;
  cout<<"3. Multiply"<<endl;
  cout<<"4. Divide"<<endl;

  cin>>choice;

  switch(choice)
  {
    case 1:
      r=a+b;
      cout<<r; break;

    case 2:
      r=a-b;
      cout<<r; break;

    case 3:

      r=a*b;
      cout<<r; break;


    case 4:

      r=a/b;
      cout<<r; break;


    default:
      cout<<"Invalid Input\n";
  }
  getch();
}


Explanation of the program
Step 1: Two variables (a and b) for storing the integers, one variable ( r ) for storing the result and one variable for switch (choice) of integer data type are declared. 

Step 2:  Message is given to the user that enter two numbers. 

Step 3: The values of a and b is taken by the input function. 

Step 4:  Now the message is given to the user that what operation he want to perform on the integers. endl works same as "\n". endl means end of line so it is also used for new line.  

Step 5: Now the value of choice is taken from the user by input function. 

Step 6: Now we are switching the choice by the switch function, suppose user entered 3, now the control will leave the other cases and will directly come to case 3 and will executes the statements of case 3, and for stopping the control from going to the next case we use break function.

If the user will enter any value which is not between the cases means not between 1 to 4 the control will go to default and will execute the statements from default. 
Output of The Above Program
Share if you liked this Post using your favorite sharing service:

Subscribe Updates, Its FREE!

0 comments:

Post a Comment

 
Related Posts Plugin for WordPress, Blogger...