Why we should use Switch Case ?
- One of the classic problem encountered in nested if-else / else-if ladder is called problem of Confusion.
- It occurs when no matching else is available for if .
- As the number of alternatives increases the Complexity of program increases drastically.
- 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;
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 -
- 3 is assigned to integer variable ‘roll‘
- On line 5 switch case decides - “We have to execute block of code specified in 3rd case“.
- Switch Case executes code from top to bottom.
- It will now enter into first Case [i.e case 1:]
- It will validate Case number with variable Roll. If no match found then it will jump to Next Case..
- When it finds matching case it will execute block of code specified in that case.