Tuesday, August 9, 2011

C Programming: Switch Statement

In the previous lesson we used a  if... elseif statement in order to execute different block of code for each different condition. As mentioned, we could use as many "elseif"s as we like.

If you have many conditions, switch statements are a more efficient way of doing this. The computer will execute a switch statement quicker than multiple "elseif"s. Also, there's actually less code for the programmer to write.

General Syntax

switch (expression)  {  case value1     code to be executed if the expression is equal to value1;     break;  case value2     code to be executed if the expression is equal to value2;     break;  case value3     code to be executed if the expression is equal to value3;     break;  default     (optional) code to be executed if none of the above conditions are true.     break;  }

Example:

Suppose following countries are given the following code. Nepal = 1, India = 2, Bangladesh = 3, Bhutan = 4, Maldives = 5, Pakistan  = 6 and Shree Lanka = 7. Now when users enter the code you have to display the name of corresponding country. In this case it is better to use switch statement although same task can be down with if else ladder.

  1: int code;
  2: printf("Enter the code:");
  3: scanf("%d",&code);
  4: switch(code){ //start switch statement
  5:    case 1:
  6:        printf("Nepal");
  7:        break; //must be written
  8:    case 2:
  9:        printf("India");
 10:        break;
 11:    case 3:
 12:        printf("Bandladesh");
 13:        break;
 14:    case 4:
 15:        printf("Bhutan");
 16:        break;
 17:    case 5:
 18:        printf("Maldives");
 19:        break;
 20:    case 6:
 21:        printf("Pakistan");
 22:        break;
 23:    case 7:
 24:        printf("Srilanka");
 25:        break;
 26:    default: //executes if user enters other than 1-7
 27:        printf("Invalid Choice");
 28:     }

Note: Break statement must be written in each case because only one statement should be executed at a time.