Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Unit 2- Switch Case

Programming in C
Dr. Nivedita Palia
SWITCH CASE
switch(var)// possible values for var
{
case val1: //if var=1 this case executes
stmt;
break;
case val2: //if var=2 this case executes
stmt;
break;
default: //if var is something else this will execute
stmt;
}
Switch Case

If no condition matches, the default is executed

If no default, nothing is done (not an error)

The break is important


SWITCH CASE
switch ( day )
{
case 0: printf (“Sunday\n”) ;
break ;
case 1: printf (“Monday\n”) ;
break ;
.
.
.
case 6: printf (“Saturday\n”);
break ;
default: printf (“Error -- invalid day.\n”) ;
break;
}
Tips
• Even if multiple statements are to be in each
case , there is no need to enclose them within
a pair of braces.
• Every statement in switch must belong to
some case
• If no default case and no case is satisfied then,
control simply falls through the entire switch
• If we want to execute a common set of
statements for multiple cases.
int main()
{ char ch;
printf (“Enter any one of the alphabets a or b”);
scanf (“%c”, &ch);
switch (ch)
{ case ’a’ :
case ’A’ :
printf (“a as in all\n”);
break;
case ’b’ :
case ’B’ :
printf (“b as in brain\n”);
break;
default :
printf (“wish you knew what are alphabets\n”);
return 0; } }
Switch Vs If-else
• A float expression cannot be tested using
switch
• Cases can never have variable expression as in
case a+3:
Switch Case

// WAP to print day of week , after getting input from user in a variable.
//WAP to construct calculator
END

You might also like