Right Click to Search

Tuesday, December 22, 2024

switch case in C Programming Language



Switch case in C Programming

  • 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
  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main()
  4. {
  5. int roll = 3 ;
  6. switch ( roll )
  7.        {
  8.        case 1 : 
  9.                  printf ( " I am Pankaj ");
  10.                  break;
  11.        case 2 : 
  12.                  printf ( " I am Nikhil ");
  13.                  break;
  14.        case 3 : 
  15.                  printf ( " I am John ");
  16.                  break;
  17.        default :
  18.                  printf ( "No student found");
  19.                  break;
  20.         }
  21. getch()
As explained earlier
  1. 3 is assigned to integer variable 'roll'
  2. As control goes to line number 6 above switch case will replace the 'roll' by 3 So temporarily line 6 changes to switch ( 3 )
  3. This checks matching case having expression '3'
  4. As it founds the matching case it Executes the body and output as ' I am John '
  5. After executing the body , break takes control out of the switch case i.e line number 21
  6. Suppose no matching case found then default case and its body  is executed 


Flowchart of Switch case :( click on image )








Bookmark & Share

Tags / Keywords : |

Stumble
Delicious
Technorati
Twitter
Facebook

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

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates