Tuesday, March 8, 2011

Switch Case in C

The switch case is a good decision making statement in C language , as if statement has very much complexity in its structure and its difficult to handle multiple decision in with if..else .

  • The function of switch statement is to read the variable associated with it as (switch(variable)) and then it check the list of case , the value which matches ,with the case the function or statement associated with it is executed.

Structure of switch-case

variable;
switch (variable)
{
       case value-1:
      lines to be executed-1;
      break;
      case value-2:
      lines to be executed-1;
      break;
}

statements to be executed;


        Look friends in this above switch-case statements , the value-1 , value-2 are the title of the case
when any user type this title or value the corresponding lines associated with the case are executed respectively.
  • So remember friends when in above structure if you type value-1 then“lines to be executed-1;” this particular line will be executed and program will run further and it will return to “statements to be executed;” statement in program
  • Always remember that break function is necessary because if don,t use it your program will execute but suppose if you choose some value then all above values will be executed , and all line,s associated with it will be printed in program .

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int day ; //day is variable which stores input integer value from user
clrscr();

printf("\nenter the number and u will know the day\n\n ");
scanf("%d",&day);

switch(day)
{
   case 1:
      printf("MONDAY");
   break;
   case 2:
      printf("TUESDAY");
   break;
   case 3:
      printf("WEDNESDAY");
   break;
   case 4:
      printf("THURSDAY");
   break;
   case 5:
      printf("FRIDAY");
   break;
   case 6:
      printf("SATURDAY");
   break;
   case 7:
      printf("SUNDAY");
   break;
}
getch();
}