THE SWITCH STATEMENT

THE SWITCH STATEMENT

We can design a program using if statements to control the selection. However, the complexity of such a program increases dramatically when the   number of alternatives increases. The program becomes difficult to read and follow. C has a bult-in multiway decision statement known as a switch. The switch statement test the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as  shown below:

The expression is an integer expression or characters. Value-1, value-2 ... are  constants are known as case lables. Each of these values should be unique within a swich statement. block-1, block-2 ..... are statement
 lists. There is no need to put braces around these blocks. Note that case labels end with a colon(:). When the switch is executed, the value of the expression is successively compared against the values value-1, value-2, ..... . If a case is found whose value matches with the value of the expression, then the block of statements that
follows the case are executed.:

The Switch Statement is shown below:
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
.........
default:
default-blcok;
break;
} statement-x;

The traffic light program (switch)
A program that displays the recommended actions depending on the color of a traffic light. Unlike the previous program, this implementation uses the switch statement.
#include <stdio.h>
int main (void)
{
 char colour;
 /* ask user for colour */
   printf ("Enter the colour of the light (R,G,Y,A): ");
   scanf ("%c", &colour);
   /* test the alternatives */      
   switch (colour)
   {
       /* red light */
       case 'R':
       case 'r':
                 printf ("STOP! \n");
                 break;
  /* yellow or amber light */
       case 'Y':
       case 'y':
       case 'A':
       case 'a':
                 printf ("CAUTION! \n");
                 break;
          /* green light */
       case 'G':
       case 'g':
                 printf ("GO! \n");
                 break;
     /* other colour */
       default:
                 printf ("The colour is not valid.\n");
   }
 return (0);
}

Comments