Programming C++ Secations Five
Programming C++ Secations Five
63
Selection statements: Switch Statement.
The switch control statement that allows us to make a decision from the number
of choices
Switch (Expression )
Expression It could be an integer constant like
{ Switch (10.0);
(10);
1, 2 or 3, or an expression that evaluates to an
case constant 1 :
Action statements;
float
Int i ;i ; .
integer
Switch (i);
break ; Constant
Case 50: : is a specific value.
case constant 2 : switch
Case >= ( i +50;
j*k)
Action statements; Case 40 a++10;
b;
break ; switch ( 23 + 45 % 4 * k )
case constant 3 :
Action statements;
break ;
default :
Action statements;
}
64
65
int i; char ch = 'x' ;
Cin>>I;
switch ( i ) switch ( ch )
{ {
case 10 : case 'v' :
Cout << "I am in case 1 \n“ ; Cout<< "I am in case v \n“ ;
break ; break ;
case 20 : case 'a' :
Cout << "I am in case 2 \n“ ; Cout<< "I am in case a \n“ ;
break ; break ;
case 30 : case 'x' :
Cout << "I am in case 3 \n“ ; Cout<< "I am in case x \n” ;
break ; break ;
default : default :
Cout << "I am in default \n“ ; Cout<< "I am in default \n„ ;
} }
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
66
switch (grade)
{
if ( marks >= 90 && marks <= 100)
case 90 :
cout << "A\n“ ;
cout <<"You Got A \n"; break;
else if (marks >= 80 && marks <90 )
cout << "B\n”;
case 80 :
else if (marks >= 70 && marks <80 )
cout <<"You Got B \n"; break;
cout << "C\n”;
else if (marks >= 60 && marks <70 )
case 70 :
cout << "D\n”;
cout <<"You Got C \n"; break;
else
cout << "F\n“ ;
case 60 :
cout <<"You Got D \n"; break;
default :
cout <<" Sorry , You Got F \n";
}
67
Switch Versus IF – Else IF
• There are some things that you simply cannot do with a switch. These
are:
– A float expression cannot be tested using a switch
– Cases can never have variable expressions (for example it is wrong to
say case a +3 : )
– Multiple cases cannot use same expressions.
68