Module 1 & 2 Third
Module 1 & 2 Third
Module 1 & 2 Third
C Switch Statement
• The switch statement in C is an alternate to if-else-if ladder statement which
allows us to execute multiple operations for the different possibles values of a
single variable called switch variable.
• Here, We can define various statements in the multiple cases for the different
values of a single variable.
1
PRESENTATION TITLE
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
2
PRESENTATION TITLE
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in
the case, all the cases will be executed present after the matched case. It is known as fall through the
state of C switch statement.
3
PRESENTATION TITLE
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
4 }
PRESENTATION TITLE
Flowchart of Switch
Statement
6
PRESENTATION TITLE
This keyword is used to stop the execution inside a switch block. It helps to terminate the
switch block and break out of it. When a break statement is reached, the switch
terminates, and the flow of control jumps to the next line following the switch statement.
The break statement is optional. If omitted, execution will continue on into the next
case. The flow of control will fall through to subsequent cases until a break is reached.
7
PRESENTATION TITLE // C Program to demonstrate the behaviour of switch case
// without break
#include <stdio.h>
int main()
{
int var = 2;
Output
// switch case without break
switch (var) { Case 2 is executed.
case 1:
printf("Case 1 is executed.\n"); Case 3 is executed.Case 4 is executed.
case 2:
printf("Case 2 is executed.\n");
case 3:
printf("Case 3 is executed.");
case 4:
printf("Case 4 is executed.");
}
8 return 0;
}
PRESENTATION TITLE
The default keyword is used to specify the set of statements to execute if there is no case
match.
It is optional to use the default keyword in a switch case. Even if the switch case statement
does not have a default statement, it would run without any problem.
9
PRESENTATION TITLE
11
// C program to print the day using switch
PRESENTATION TITLE #include <stdio.h>