Professional Documents
Culture Documents
(C++ Language)
switch (<expression>){
case <constant1>:
<Statements1>;
break;
case <constant2>:
<Statements2>;
break;
...
...
default:
<Statementsn>; }
Execution:
• The expression following the keyword switch can either be an integer expression or a character
expression.
• An integer or a character constant follows the keyword case.
• Based on the value returned by the expression, the respective case is executed.
• The expression is first evaluated and this value is then matched against the constants in each
case.
• When a match is found, the statements following that particular case statement are executed. If
no match is found, the statements following the default case are executed.
Execution:
• The keyword break must be included in each case.
• A break statement will enable you to skip all the
cases following the current case and
• Transfer the control outside the switch statement.
• The break statement need not be included in the
default case.
• After executing the statements in the default case,
the control exits the switch statement
automatically.
#include <iostream.h> Program to illustrate the working of a
void main() { switch statement
int x;
cout<<"\n Enter the value for X (1,2 or 3) : ";
cin>>x;
switch (x) {
case 1:
cout<<" You have entered One ";
break;
case 2:
cout<<" You have entered Two ";
break;
case 3:
cout<<" You have entered Three ";
break;
default:
cout<<" Wrong Entry “; }
}
Sample Output :
Output 1:
Enter the value for X (1,2 or 3) : 1
You have entered One
Output 2:
Enter the value for X (1,2 or 3) : 5
Wrong Entry
Summary
char grade;
if ( grade == 'A' || grade == 'a' )
cout<<" Your get grade " <<grade<<" Congratulation";
else if ( grade == 'B' || grade == 'b' )
cout<<" Your get grade " <<grade<<" Good";
else if ( grade == 'C' || grade == 'c' )
cout<<" Your get grade " <<grade<<" Need more exercise";
else if ( grade == 'D' || grade == 'd' )
cout<<" Your get grade " <<grade<<" Need improvement";
else if ( grade == 'F' || grade == 'f' )
cout<<" Your get grade " <<grade<<" Try again ";
else
{
cout<< "Incorrect letter grade entered." ;
cout<< " Enter a new grade.\n" ;
}