SWITCH STATEMENT


The control statement which allows us to make a decision from the number of choices is called a switch. Switch case statements are a substitute for long if statements that compare a variable to several integral values.

They most often appears as follows:

switch(expression) {

   case constant-expression  :
      statement(s);
      break; /* optional */
 
   case constant-expression  :
      statement(s);
      break; /* optional */
  
   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

The expression following the keyword switch is any C expression that will yield an integer value.The keyword case is followed by an integer or a character constant. Each constant in each case must be different from others. The value returned from the expression is then compared to the values in different cases, where it matches that block of code is executed, if there is no match, then default block is executed.


Example


#include <stdio.h>
 
int main () {

   
   char grade = 'A';

   switch(grade) {
      case 'A' :
         printf("Excellent!\n" );
         break;
      case 'B' :
         printf("Well done\n" );
         break;
      case 'C' :
         printf("You passed\n" );
         break;
      case 'D' :
         printf("Better try again\n" );
         break;
      default :
         printf("Invalid grade\n" );
   }
   
   printf("Your grade is  %c\n", grade );
 
   return 0;
}


Comments

Popular posts from this blog

INTERFACING SEVEN SEGMENT DISPLAY WITH 89c51

INTERFACING OF LCD WITH 89C51

POINTERS