Switch Statement
Notre Dame University Bangladesh
Presented by:
[Link] Das
ID: 201120008
[Link] Chowdhury
ID: 201120010
[Link] Islam Orpa
ID: 201120019
Outlines
Switch Case
Flow Chart of Switch Case
Creating Menus
Switch – syntax
Switch Example
Switch Default
To Switch or not To Switch
Uses of Switch Case
Summary
Switch Case
Switch case statement allows us to make decisions from multiple choices.
Integer expression must hold integer values like 1,2,3 etc. The keyword case is
followed by an integer or a character constant.
Each constant in each case must be different from others.
Break statement can be used to terminate a statement sequence. When a break
statement is encountered the loop is immediately terminated and compilation
resumes at the next statement following the loop.
Default case can be used for performing a task when none of the cases is true. No
break is needed in the Default case.
Creating Menus
If we want to give user a choice on what to do next, we
can display a set of options. Then the user can enter
his/her choice . A notice should be given so that the user
can understand which type of input to enter.
SWITCH-SYNTAX
If the
expression
matches value-
1, 2 or 3 control
jumps to Block-
1, 2 or 3 .
Else the control
will jump to
default .
Switch Example
Switch-Default
A switch statement can have an optional default case
The default case has no associated value and simply uses the reserved word
default
If the default case is present, control will transfer to it if no other case value
matches
If there is no default case and no other value matches, control falls through to
the statement after the switch
Switch with default case example
To switch or not To switch
The expression of switch statement must result in an Integral type, meaning
an integer(byte, short, int, long) or a char
It cannot be a Boolean value or a floating point value (float or double)
The implicit Boolean condition in a switch statement is equality
You cannot perform relational checks with a switch statement
Why Use a switch case?
A nested if-else structure is just as efficient as a switch case .
However, a switch case may be easier to read.
Also, it is easier to add new cases to a switch case than to a nested if-
else structure .
Summary
Switch case statement can be used to create options in a program .
It allows a variable to be tested for equality against a list of values. Each
value is called a case.
The break statement can be used as the last statement in each case’s
statement list
A break statement causes control to transfer to the end of the switch
statement. If a break statement is not used, the flow of control will continue
into the next case.
Thank You