-->

Switch Statement


A switch statement allows a variable or value of an expression to be tested for equality against a list of possible case values and when match is found, the block of code associated with that case is executed.
Syntax of Switch Statement
switch(expression) {
case constant1 : /* code block1 */
statement1; break;
case constant2 : /* code block 2 */ statement; break; case constant3 : /* code block 3 */ statement; break;
default : /* Optional */ statement; }
Flow chart

Rules for using switch:
1. The expression (after switch keyword) must yield an integer value i.e it can be an integer or a variable or an expression that evaluates to an integer.
2. The case label i.e values must be unique.
3. The case label must end with a colon(Description: https://static.xx.fbcdn.net/images/emoji.php/v9/fce/1/18/1f642.png:)
4. The following line, after case statement, can be any valid C statement.
Example
#include <stdio.h>
 int main ()
 { char grade = 'B';
 switch(grade)
{ case 'A' : printf("Excellent!\n" );
break;
case 'B' : printf("Well done\n" );
break;
 case 'C' : printf("Good\n" );
 break;
case 'D' : printf("You passed\n" );
 break;
case 'F' : printf("Better try again\n" );
break;
default : printf("Invalid grade\n" );
}
 printf("Your grade is %c\n", grade );
return 0; }
The output of the above program is : Well done Your grade is B


No comments:

Post a Comment

Basic structure of c program