Thursday 5 March 2015

Switch statement in C++cases, break and defult conditon

Switch statement in C++ It is use to select different choose in a C++ program. It is similar to if statement but in this we can only ... thumbnail 1 summary

Switch statement in C++


It is use to select different choose in a C++ program. It is similar to if statement but in this we can only use number or character in its condition. There are three part of Switch statement.
Syntax
switch();
{
case 1:
Statement 1
Break;
case 2:
Statement 2
}
 


In Switch Statement when user select a curtain option so this value is compare with the value which are given in the cases in the switch statement. When the user entered value and the case value become equal then that statement will executed. Break is use as else when the first case value is match with the value that is entered by then it skips the lower part of program.
Example
#include<iostream.h>
int main()
{
int a;
cin>>a;
switch(a)
{
case 1:
cout<<"it is case 1";
break;
case 2:
cout<<"it is case 2";
}
system("pause");
return 0;
};
Example 2
#include<iostream.h>
int main()
{
int a;
cout<<"To Buy  mobile press 1  To sell  mobile press 2";
cin>>a;
switch(a)
{
case 1:
cout<<"welcome here you can buy mobile";
break;
case 2:
cout<<"welcome here you can sell mobile";
}
system("pause");
return 0;
};



Example 3
#include<iostream.h>
int main()
{
int a=6;
int b=3;
int select;
cout<<"For addition press 1 and For subtraction press 2 "<<endl;
cin>>select;
switch(select)
{
case 1:
cout<<a+b;
break;
case 2:
cout<<a-b;
}
system("pause");
return 0;
};
Use of  Default in Switch statement 
The default is used instead of case and it will print the statement which is defined in the default body. It is uses when the user does not select any choose or select a wrong choose.
Syntax
switch ()
{
case 1: 
statement 1
default: 
statement 2
}
Example
#include<iostream.h>
int main()
{
int a=6;
int b=3;
int select;
cout<<"For addition press 1"<<endl;
cout<<"For subtraction press 2"<<endl; 
cin>>select;

switch(select)
case 1:
cout<<a+b;
case 2:
cout<<a-b;
defult:
cout<<"please select 1 or 2 form the above option"<<endl;
system("pause");
return 0;
};