Switch Statement
Switch Statement
• Date : 06-Jan-2025
• Program : ADP IT
• Subject : Application of Information & Communication Tech
• Topic : Switch Statement
• Presented To: Ms. Aqsa Mustafa
• Presented By: Sundas Noreen (24)
Government Graduate College, Bhalwal
Switch Statement
Definition:
A switch statement is a control flow structure that allows a variable to be tested for
equality against a list of values, each of which is called a case. It provides an efficient way to
handle multiple conditional branches based on the value of a variable. The switch statement is
another conditional structure. It is a good alternative of if-else-if statement. It can be used easily
when there are many choices available and only one should be executed.
Syntax:
The syntax for writing this structure is as follows:
switch(expression)
{
case val1:
statements 1;
break;
case val2:
statements 2;
break;
:
:
case valn:
statementn;
break;
default:
statements;
}
Flowchart:
F
Case 2 T Statement Block 2
F
Statement Block N+1
Working:
Expression Evaluation:
Switch statement compares the result of a single expression with multiple cases.
Expression can be any valid expression that results in integer or character value. The expression
is evaluated at the top of switch statement and its result is compared with different cases. Each
case label represents one choice. If the result matches with any case, the corresponding block of
statements is executed. Any number of cases can be used in one switch statement.
Default:
The default label appears at the end of all case labels. It is executed only when the
result of expression does not match with any case label. Its use is optional. The position of the
default label is not fixed. It may be placed before the first case statement or after the last one.
Break:
The break statement in each case label is used to exit from switch body. It is used at
the end of each case label. When the result of the expression matches with a case label, the
corresponding statements are executed. The break statement comes after these statements and the
control exits from switch body. If break is not used, all case blocks that come after the matching
case, will also be executed.
Example:
The following example inputs a number of weekdays and displays the name of the day. For
example, if the user enters 1, it displays "Monday" and so on.
#include <stdio.h>
#include <conio.h>
void main()
{
int n;
clrscr();
printf("Enter number of a weekday:");
scanf("%d",&n);
switch (n)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid day");
}
getch();
}
Output:
Enter number of a weekday: 3
Wednesday