Tuesday, December 30, 2008

Switch

Switch statement-
A switch statement is used in the similar way as the if …else if….statement. If there are certain number of conditions which are known then the switch statement is used. The conditions are given in the statement itself. The statement in the switch statement is executed when the condition is satisfied. The form of the statement is
Switch(x)
{
Case 1:
…..
…..
Break;
Case 2:
……
…….
Break;
Case 3:
..
..
..
Default:
….
}
The value of x is the value of the number after the case i.e.1,2,3,……
The break statement is used to go out of the switch because if it is not given then the consecutive statements after the executed statement are executed. At last the default statement is given so if the above statements are not satisfied then the default statement is executed. It is not necessary to give the default statement. The control exits from the switch statement if the condition is not satisfied.
e.g.
void main()
{
Int x;
Printf(“Enter the number less than 5”);
Scanf(“%d”,&x);
Switch(x)
{
Case 0:
Printf(“zero”);
Break;
Case 1:
Printf(“one”);
Break;
Case 2:
Printf(“two”);
Break;
Case 3:
Printf(“three”);
Break;
Case 4:
Printf(“four”);
Break;
Default:
Printf(“number is greater than or equal to five”);
}
In this program the number of cases can be increased. The statements in the cases can be of any number. There is no need of the default statement. The ‘exit()’ statement can be used in this program if a another loop is present outside the switch statement. The function can be written in the cases.
e.g.
void main()
{
int x;
do
{
printf(“enter the value”);
scanf(“%d”,&x);
switch(x)
{
Case 1:
…..
Case 2:
…..
..
..

Case 6:
Exit();
}
}while(x!=6);
In this program when user gives the value six the control exits from the program.

No comments:

Watch tv!