C switch statement

Description

To take one of a number of possible actions. switch is preferred over multiple if...else statements.

Syntax

The general form of a switch statement is


switch(switch_expr)
{//  w  w w  . j  a  v  a  2 s.  com
  case constant expr1 :  Statement1;
                         Statement2;
                         break;
  case constant expr1 :  Statement3;
                         Statement4;
                         break;
  .....
  default             :  Statement5;
                         Statement6;
                         break;
}

Example for switch statement

The clause 'default' is optional.


#include <stdio.h>
//  ww  w  . ja va 2  s.  co m
main(){
    int i,n = 5;
    for(i = 1; i<n; i= i+1){
        switch(i%2)
        {
            case 0 : printf("the number %d is even \n",i);
                     break;
            case 1 : printf("the number %d is odd \n",i);
                     break;
        }
    }
}

The code above generates the following result.


Two cases, one action


#include <stdio.h>
//from w  ww  .j a va 2s . c om
int main(void)
{
  char answer = 0;

  printf("Enter Y or N: ");
  scanf(" %c", &answer);

  switch (answer)
  {
    case 'y': case 'Y':
      printf("\nYou responded in the affirmative.");
      break;

    case 'n': case 'N':
      printf("\nYou responded in the negative.");
      break;

    default:
      printf("\nYou did not respond correctly...");
      break;
  }
  return 0;
}

The code above generates the following result.


Nest if statement in case statement


#include <stdio.h>
#include <ctype.h>
/*from   w  w  w.  j av  a  2  s.c o  m*/
int main(void)
{
  double number1 = 3.0;
  double number2 = 4.0;
  char operation = '+';
  char reply = 0;      


  switch(operation)
  {
    case '+':                    
      printf("= %lf\n", number1 + number2);
      break;

    case '-':                    
      printf("= %lf\n", number1 - number2);
      break;

    case '*':                    
      printf("= %lf\n", number1 * number2);
      break;

    case '/':
      if(number2 == 0)           
        printf("\n\n\aDivision by zero error!\n");
      else
        printf("= %lf\n", number1 / number2);
       break;

    case '%':                    
      if((long)number2 == 0)
        printf("\n\n\aDivision by zero error!\n");
      else
        printf("= %ld\n", (long)number1 % (long)number2);
      break;

    default:                     
      printf("\n\n\aIllegal operation!\n");
      break;
  }
  return 0;
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array