Jun 24, 2014

C Programming #19: Decision making - Switch

Following article will discuss yet another decision making construct in C called Switch.

Following is the syntax of switch statement

switch(expression) {
   case const-expression1:
       statement1;
       break;
   case const-expression2:
       statement2;
       break;
   default:
       default-statement;
       break;
}


First the expression is evaluated. If the value of expression matches value of const-expression (or case labels) then that particular statement under the case is executed. If none of the values of const-expression matches then statement under default is executed. Note that result of expression and const-expression should be integral (characters, integers, long etc)

Following C program will explain the switch statement.


#include <stdio.h>
int main () 
{
   int a = 10;

   switch(a % 2) {
      case 0:
         printf("%d is even number\n", a);
         break;
      case 1:
        printf("%d is odd number\n", a);
        break;
      default:
        printf("ERROR, something seriously went wrong\n");
        break;
   }
   return 0;
}

Output of above program is-


10 is even number

Explanation-
In the above program first the expression inside switch is evaluated, which is a % 2 (It is finding remainder). When a is divided by 2, result (remainder) can be either 1 or 0. If it is 0 then it means it is divisible by 2 and hence even. If it is 1 then it is not divisible by 2 and hence odd. Switch will match the answer of expression to all labels, if it matches it executes the below statement till it hits break.

Say you forget to put break, output of same program would be


10 is even number
10 is odd number
ERROR, something seriously went wrong


Further more if a were 11, output of same program would be


11 is odd number
ERROR, something seriously went wrong
Hopefully now you understand the usage of break in case statement.

It need not be that break is used always (as well as statement after the case label.
See the following example


#include <stdio.h>

int main()
{
   char val = 'i';

   switch(val) {
     case 'a':
     case 'e':
     case 'i':
     case 'o':
     case 'u':
        printf("Vowel !!\n");
        break;
     default :
        printf("Not a Vowel !!\n");
        break;

   }
   return 0;
}

Output of program is


Vowel !!

Food for thought
In above program, if val were 'A' what would be output ? How to rectify it ?

Links

Quiz - Not Yet written !!
Next Article - C Programming #20: Loop - Introduction
Previous Article - C Programming #18: Decision Making - if, else if, else
All Article - C Programming

No comments :

Post a Comment