C switch case statement



Why we should use Switch Case ?

  1. One of the classic problem encountered in nested if-else / else-if ladder is called problem of Confusion.
  2. It occurs when no matching else is available for if .
  3. As the number of alternatives increases the Complexity of program increases drastically.
  4. To overcome this , C Provide a multi-way decision statement called ‘Switch Statement

See how difficult is this scenario ?

if(Condition 1)
   Statement 1
else   
   {
   Statement 2
   if(condition 2)
      {
      if(condition 3) 
        statement 3
      else
         if(condition 4)
            {
            statement 4
            }         
      }
   else
     {
     statement 5
     }
   }

First Look of Switch Case

switch(expression)
{
case value1 : 
    body1
    break;

case value2 : 
    body2
    break;

case value3 : 
    body3
    break;

default :
    default-body
    break;  
}
next-statement;

Flow Diagram :

Syntax of Switch Case Stetement in C Programming
*Steps are Shown in Circles.

How it works ?

  • Switch case checks the value of expression/variable against the list of case values and when the match is found , the block of statement associated with that case is executed
  • Expression should be Integer Expression / Character
  • Break statement takes control out of the case.
  • Break Statement is Optional.
01:#include<stdio.h>
02:void main()
03:{
04:int roll = 3 ;
05:switch ( roll ) 
06:       {
07:       case 1: 
08:               printf ( " I am Pankaj ");
09:               break;
10:       case 2: 
11:               printf ( " I am Nikhil ");
12:               break;
13:       case 3: 
14:               printf ( " I am John ");
15:               break;
16:       default :
17:               printf ( "No student found");
18:               break;
19:        }
20:}

As explained earlier –

  1. 3 is assigned to integer variable ‘roll
  2. On line 5 switch case decides – “We have to execute block of code specified in 3rd case“.
  3. Switch Case executes code from top to bottom.
  4. It will now enter into first Case [i.e case 1:]
  5. It will validate Case number with variable Roll. If no match found then it will jump to Next Case..
  6. When it finds matching case it will execute block of code specified in that case.

See how Switch Case works using Graphical Picture

Switch Case Statement in C Programming Language