Switch Statement In C


In C Programming language, we use a switch statement when we want to test multiple condition at the same time.


Syntax of switch statement


switch(value)

{

case 1:

Statement;

case 2:

Statement;

. . . .

Default: ///optional case3 or more

Statement;

}


Simple Program of switch statement in C

A program in c to print a day of week using switch case

#include <stdio.h>

#include<conio.h>;

void main()

{

int day;

printf(“Enter A Number from week should be 1 To 7\n”);

scanf(“%d”,&day);

switch(day)

{

case 1:

printf(“It's Monday for 1”);

Break;

case 2:

printf(“It's Tuesday for 2”);

break;

case 3:

printf(“It's Wednesday for 3”);

break;

case 4:

printf(“It's Thursday for 4”);

break;

case 5:

printf(“It's Friday for 5”);

break;

case 6:

printf(“It's Saturday for 6”);

break;

case 7:

printf(“It's Sunday for 7”);

break;

default:

printf(“Invalid Input Number”);

}

getch();

}


Output:
Enter A Number from week should be 1 To 7
2
It's Tuesday for 2

We can also use switch statement with Nested switch.

Simple Program of Nested Switch statement in C


#include <stdio.h>

#include<conio.h>

void main()

{

int select;

printf(“type 1 to get Sum of two Numbers\n”);

printf(“type 2 to get Multiplication of two Numbers\n”);

printf(“type 3 to get Subtraction of two Numbers\n”);

printf(“type 4 to get Division of two Numbers\n”);

scanf(“%d”,&select);

printf(“Enter two Number”);

scanf(“%d%d”,&x,&y);

switch(select)

{

case 1:

printf(“The sum of two Number :%d”,x+y);

Break;

case 2:

printf(“Multiplication of two Number is :%d”,x*y);

break;

case 1:

printf(“Substraction of two Number is :%d”,x-y);

break;

case 4:

{

printf(“Press 1 for quotient of two Number”);

printf(“Press 2 for Remainder of two Number”);

scanf(“%d”,&select);

switch(select)

{

case 1:

printf(“The quotient of two Number (a/b) is :%d”,x/y);

break;

case 2:

printf(“The Remainder of two Number is (a%b) :%d”,x%y);

break;

}

break;

}

default:

printf(“Invalid Input!”);

}

getch();

}


Output:
Press 1 to get Sum of two Number
Press 2 to get Sum of two Number
Press 3 to get Sum of two Number
Press 4 to get Sum of two Number
2

Enter two Number
12
2
Multiplication of two Number is:24