Switch Statement in C

This “Switch statement in C Language” page explains clearly what is switch case , syntax and how to use switch-case in C logical programming.


 

switch :

  • Conditional control statement.
  • Used to define more than one block is called “case”
  • Executes a specific block by checking the condition randomly.
  • Default case executes if specified case doesn’t match.
  • Default case is optional.
  • Default case can be placed any where in switch statemnt

 

syntax :
switch(<var> or <expr>)
{
case 1    :    //statements;
case 2    :    //statements;
…..
case n    :    //statements;
default     :    //statements;
}

 

Note :
    Statements of a specific case need not placed inside a block.
    Default case is optional.
    Default case can be placed anywhere in the switch statement.

 

#include<stdio.h>
main()
{
char ch;
printf(“Enter one char(r,g,b) :”);
scanf(“%c”,&ch);

switch(ch)
{
case ‘r’    :    printf(“red\n”);
break;
case ‘g’    :    printf(“green\n”);
break;
case ‘b’    :    printf(“blue\n”);
break;
default  :    printf(“no color\n”);
}
}

Default case can be placed anywhere in the switch statement.
#include<stdio.h>
main()
{
int i=6;
switch(i)
{
default        :    i+=2;
case 0        :    i=2;
case 1        :    i++;
case 2        :    i+3;
case 3        :    ++i;
break;
}
printf(“i : %d\n”,i);
}

 

#include<stdio.h>
main()
{
int i;
for(i=1 ; i<=25 ; i++)
{
switch(i)
{
case 0         :    i+=5;
case 1         :    i+=4;
case 2         :    i+=2;
case 3         :    i+=2;
default        :    i+=4;
break;
}
printf(“i : %d\n”,i);
}
}

Share this