×
☰ Menu

Switch Statements

The control statement that allows us to make a decision from the number of choices is called a switch.

 

Syntax of switch

switch ( choice ) 
{ 
case 1 : 
statement 1 ; 
break ; 
case 2 : 
statement 2 ; 
break ; 
….
……
default:
statement ;
break;
}

 

How Switch Statements 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.

 

Sample Program on switch statement

void main( )
{
int per;
printf("enter per:\n");
scanf("%d",&per);
if(per>=60)
per=6;
else
per=per/10;
switch(per)
{
case 6: 
printf ( "First division" ) ;
break;
case 5:
printf ( "Second division" ) ;
break;
default:
printf ( "fail" ) ;
}
getch();
}

 

Rules for Switch values

    • Case Label must be unique
    • Case Labels must ends with Colon
    • Case labels must have constants
    • Case label must be of Integer, Character type
    • Case label should not be ‘floating point number ‘
    • Default label is Optional.
    • Relational and logical Operators are not allowed in Switch Statement.