Switch case in C Programming
Must Read :
Switch CaseWhy Need arises ?
Rules of using switch
Illegal ways of Using switch
Valid Ways of using switch case
Switch case : Tricky Questions ?
- 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 multiway decision statement called 'switch'
Syntax :
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.
Example and Steps of Execution :
- #include<stdio.h>
- #include<conio.h>
- void main()
- {
- int roll = 3 ;
- switch ( roll )
- {
- case 1 :
- printf ( " I am Pankaj ");
- break;
- case 2 :
- printf ( " I am Nikhil ");
- break;
- case 3 :
- printf ( " I am John ");
- break;
- default :
- printf ( "No student found");
- break;
- }
- getch()
- }
- 3 is assigned to integer variable 'roll'
- As control goes to line number 6 above switch case will replace the 'roll' by 3 So temporarily line 6 changes to switch ( 3 )
- This checks matching case having expression '3'
- As it founds the matching case it Executes the body and output as ' I am John '
- After executing the body , break takes control out of the switch case i.e line number 21
- Suppose no matching case found then default case and its body is executed
Flowchart of Switch case :( click on image )

Bookmark & Share
0 Comments:
Post a Comment
Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email