Lecture - 09 (Switch)
Lecture - 09 (Switch)
LECTURE-9: SWITCH
STATEMENT
Computer Programming
1
TODAY WE WILL COVER
10/12/2024
Switch Statement
THE SWITCH STATEMENT
10/12/2024
Used to select among statements from
several alternatives
In some cases, can be used instead of
if/else if statements
switch (expression)
//integer
{
case exp1: statement1;
case exp2: statement2;
...
case expn: statementn;
3
default: statementn+1;
}
SWITCH STATEMENT
FORMAT
10/12/2024
SWITCH STATEMENT REQUIREMENTS
10/12/2024
1) expression must be an integer variable or
an expression that evaluates to an integer
value
2) exp1 through expn must be constant integer
expressions or literals, and must be unique
in the switch statement
3) default is optional but recommended
5
THE SWITCH STATEMENT
10/12/2024
6
SWITCH STATEMENT-HOW IT WORKS
10/12/2024
1) expression is evaluated
2) The value of expression is compared
against exp1 through expn.
3) If expression matches value expi, the
program branches to the statement
following expi and continues to the end of
the switch
4) If no matching value is found, the program
branches to the statement after default:
7
BREAK STATEMENT
10/12/2024
Used to exit a switch statement
If it is left out, the program "falls through"
8
TASK-1: WRITE A SWITCH PROGRAM FOR THE FOLLOWING
OUTPUT
10/12/2024
9
USING SWITCH IN MENU SYSTEMS
10/12/2024
switch statement is a natural choice for
menu-driven program:
display the menu
then, get the user's menu selection
use user input as expression in switch
statement
use menu choices as expr in case statements
10
PRACTICE!
10/12/2024
Write a program to build a simple calculator
using switch Statement.
The output of the program is shown below.
11
10/12/2024
12
DIFFERENCE B/W SWITCH AND IF-ELSE
10/12/2024
Number of options
• If-else statements are used to choose between two options, while
switch statements are used to choose among multiple options.
• Data types
• If-else statements can compare values of all data types, including
integer, float, string, and character. Switch statements can only
compare integer and character values.
• Conditions
• If-else statements can check for complex conditions formed using
relational operators. Switch statements can only check for
equality conditions.
Execution
If-else statements evaluate conditions independently, while
switch statements have a built-in fall-through functionality.
Editing
If-else statements can be difficult to edit, while switch statements 13
are generally easier to modify.
10/12/2024
Questions
14