Switch case is useful where we have to select a choice between n numbers of alternatives. It is like if-else-if ladder statement.
switch (variable) { case value1: statement 1; statement 2; break; case value2: statement 1; statement 2; break; default: statement 1; statement 2; }
Some valid switch syntax:
int x=5, y=10; switch(x) switch(x>y) switch(x+y-2)
Some invalid switch syntax:
float f=10.0f, g=20.2f ; switch(f) switch(f+g) switch(f+2.5)
Some valid case syntax:
case 3: case 1+2: case 'a': case 'a'>'b':
Some invalid case syntax:
case 2.5: case x: case x+2: case 1,2,3:
Example 1: WAP to explain the use of fall through statement in switch case. 206
void main() { int n; clrscr(); printf("Enter number: (1-5) "); scanf("%d",&n); switch(n) { case 1: printf("\nNumber is equal to 1."); case 2: printf("\nNumber is equal to 2."); case 3: printf("\nNumber is equal to 3."); case 4: printf("\nNumber is equal to 4."); case 5: printf("\nNumber is equal to 5."); default: printf("\nInvalid Input"); } getch(); }
Above program is an example of fall through statement. Re-write the above program and apply break keyword at end of each case.
switch(n) { case 1: printf("\nNumber is equal to 1."); break; case 2: printf("\nNumber is equal to 2."); break; case 3: printf("\nNumber is equal to 3."); break; case 4: printf("\nNumber is equal to 4."); break; case 5: printf("\nNumber is equal to 5."); break; }