Switch Statement in C

Switch statement in C programming statement allows you to control and execute the specific block of code among many alternatives, otherwise, execute the default block.

General form of Switch Statement


switch(integer expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant 3:
do this;
default:
do this;
}

Program using Switch Statement

Program

#include<stdio.h>
#include<conio.h>
void main()
{
int i = 2;
switch(i) //switching on 'i' value.
{
case 1: //if 'i' have 1 then
printf("I am in case 1"); //print this and
break; //break the statement.
case 2: //if 'i' have 2 then
printf("I am in case 2"); //print this and
break; //break the statement.
case 3: //if 'i' have 3 then
printf("I am in case 3"); //print this and
break; //break the statement.
default: //if not in above then
printf("I am in default"); //print this.
}
getch();
}
Output
I am in case 2

Program Using Switch Statement on Char Value

Program

#include<stdio.h>
#include<conio.h>
void main()
{
char c = 'f'; //assigning 'f' to 'c'.
switch(c) //apply switch statement on 'c' value.
{
case 'v': //if 'c' have 'v' have then
printf("I am in case v"); //print this and
break; //break the statement.
case 'a': //if 'c' have 'a' have then
printf("I am in case a"); //print this and
break; //break the statement.
case 'f': //if 'c' have 'f' have then
printf("I am in case f"); //print this and
break; //break the statement.
default: //if not in above then
printf("I am in default"); //print this.
}
getch();
}
Output
I am in case f

Program Switching on User Enter Value
Program

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter any of the alphabet a, b, or c: ");
scanf("%s", &ch); //user enter value storing in 'ch'.
switch(ch) //switching on 'ch' value.
{
case 'a': //if 'ch' have 'a' Or
case 'A': //'A' value then
printf("a as in ashar"); //print this and
break; //break the statement.
case 'b': //if 'ch' have 'b' Or
case 'B': //'B' value then
printf("b as in brain"); //print this and
break; //break the statement.
case 'c': //if 'ch' have 'c' Or
case 'C': //'C' value then
printf("c as in cookie"); //print this and
break; //break the statement.
default: //if not in above then
printf("wish you knew what are alphabets"); //print this.
}
getch();
}
Output
Enter any of the alphabet a, b, or c: B
b as in brain