Monday, 19 March 2012

The Switch Statement

The Switch Statement:-
         Instead of using the if-else-if ladder, the switch statement is available for handling multiple choices.
          Systax:-  Switch(variable)
                          {
                                 case constant 1;
                                 statement (s);
                                 break;
                                 case constant 2;
                                       statement(s);
                                 break;
                               case constant 3;
                                       statement(s);
                               break;
                               default
                                      statement(s);
                         }

          Variable between the parentheses following the switch keyword is used to test the conditions and is called as the control variable. If result is evaluated as “constant1”, the “case constant1” is executed. If the value evaluated as “Constant2”, the “case constant2;” is executed, and so on. If the value of the variable does not correspond to any case, the default case is executed.
          The ‘break’ statement is important to transfer the control out of the switch statement.

Example:-

#include <stdio.h>
int main()
{
     char c;
     printf(“Please make your treat selection:\n”);
      printf(“1 - Beverage.\n”);
      printf(“2 - Candy.\n”);
      printf(“3 - Hot dog.\n”);
      printf(“4 - Popcorn.\n”);
      printf(“Your choice:”);
/* Figure out what they typed in. */
      c=getchar();
    switch(c)
   {
       case ‘1’:
               printf(“Beverage\nThat will be $8.00\n”);
       break;
       case ‘2’:
               printf(“Candy\nThat will be $5.50\n”);
        break;
       case ‘3’:
               printf(“Hot dog\nThat will be $10.00\n”);
        break;
       case ‘4’:
              printf(“Popcorn\nThat will be $7.50\n”);
       break;
default:
            printf(“That is not a proper selection.\n”);
            printf(“I’ll assume you’re just not hungry.\n”);
            printf(“Can I help whoever’s next?\n”);
  }
      return(0);
     }

No comments:

Post a Comment