Introduction
You can use a switch statement when you want to check multiple conditions. It can also be done using an if statement but it will be too lengthy and difficult to debug.
Program/Example
The general format for a switch statement is
switch (expressions) { case constant expressions }  Example of a case constant expression and column:
switch (i/10) {     case 0: printf ("Number less than 10");    // A                 break;     case 1: printf ("Number less than 20");     // B                 break;     case 2: printf ("Number less than 30");    // C                 break;     default: printf ("Number greater than or equal to 40");    // D                 break; } Explanation
-  The switch expression should be an integer expression and, when evaluated, it must have an integer value. 
-  The case constant expression must represent a particular integer value and no two case expressions should have the same value. 
-  The value of the switch expression is compared with the case constant expression in the order specified, that is, from the top down. 
-  The execution begins from the case where the switch expression is matched and it flows downward. 
-  In the absence of a break statement, all statements that are followed by matched cases are executed. So, if you don't include a break statement and the number is 5, then all the statements A, B, C, and D are executed. 
-  If there is no matched case then the default is executed. You can have either zero or one default statement. 
-  In the case of a nested switch statement, the break statements break the inner switch statement. 
Point to Remember
The switch statement is preferable to multiple if statements.
 
No comments:
Post a Comment