Tuesday, May 12, 2009

Switch Case statements

The Switch Case Statement

The switch statement is used to pickup or execute a particular group of statements from several available group of statements. It allows us to makie a decision from the number of choices.
It is a multiway decision statement, it tests the value of given variable or expression against a list of case values and when a match is found, a block of statements associate with that case is executed.

Syntax:

switch(expression)
{
case 1: statements;
break;
case 2: statements;
break;
case 3: statements;
break;

case n: statements;
break;

default : statements;
break;

}

The integer expression following the key word switch is any ‘C’ expression that must yield an integer value. It must be an integer constant like 1,2,3 or an expression that evaluates to an integer.
The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the other.
First the integer expressions following the keyword switch is evaluated. The value it gives is we arched against the constant value that follow the case statements. When a match is found, the program executed the statements following the case. If no math is found with any of the case statements, then the statements following the default are executed Rules for writing switch() Statement.

The expression in switch statement must be an integer value or a character constant.
No real numbers are used in expression.
Each case block and default blocks must end with break statements
The default is optional
The case keyword must terminate with colon (:)
No two case constants are identical

Example : For printing Months of a year using switch case statement

void main()
{
int n;
clrscr();
cout<<"Enter the Number of N: ";
cin>> n;
switch(n)
{
case 1: cout<<"January"
break;

case 2: cout<<"Febuary"
break;

case 3: cout<<"March"
break;

case 4: cout<<"April"
break;

case 5: cout<<"May"
break;

case 6: cout<<"June"
break;

case 7: cout<<"July"
break;

case 8: cout<<"August"
break;

case 9: cout<<"September"
break;

case 10: cout<<"October"
break;

case 11: cout<<"November"
break;

case 12: cout<<"December"
break;

default: cout<<"U have to enter Number 1-12"
break;
}
getch();
}

Output will be

Enter the Number of N: 6
June

Enter the Number of N: 5
May

Enter the Number of N: 15
U have to enter Number 1-12

No comments:

Post a Comment