Introduction
When you want to take one of a number of possible actions and the outcome depends on the value of the expression, you can use the switch statement. switch is preferred over multiple if...else statements because it makes the program more easily read.
Program
#include
main()
{
int i,n; //the
scanf("%d",&n); for(i = 1; i
{
switch(i%2) // statement A
{
case 0 : printf("the number %d is even \n",i); // statement B
break; // statement C
case 1 : printf("the number %d is odd \n",i);
break;
}
}
}
/*
5
the number 1 is odd
the number 2 is even
the number 3 is odd
the number 4 is even
*/
Explanation
The program demonstrates the use of the switch statement.
1. The general form of a switch statement is
2. Switch(switch_expr)
3. {
4. case constant expr1 : S1;
5. S2;
6. break;
7. case constant expr1 : S3;
8. S4;
9. break;
10. .....
11. default : S5;
12. S6;
13. break;
14. }
15. When control transfers to the switch statement then switch_expr is evaluated and the value of the expression is compared with constant_expr1 using the equality operator.
16. If the value is equal, the corresponding statements (S1 and S2) are executed। If break is not written, then S3 and S4 are executed. If break is used, only S1 and S2 are executed and control moves out of the switch statement.
17. If the value of switch_expr does not match that of constant_expr1, then it is compared with the next constant_expr. If no values match, the statements in default are executed.
18. In the program, statement A is the switch expression. The expression i%2 calculates the remainder of the division. For 2, 4, 6 etc., the remainder is 0 while for 1, 3, 5 the remainder is 1. Thus i%2 produces either 0 or 1.
19. When the expression evaluates to 0, it matches that of constant_expr1, that is, 0 as specified by statement B, and the corresponding printf statement for an even number is printed. break moves control out of the switch statement.
20. The clause ‘default’ is optional.
Point to Remember
The switch statement is more easily read than multiple if...else statements and it is used when you want to selectively execute one action among multiple actions.
No comments:
Post a Comment