0% found this document useful (0 votes)
2 views

Lecture 5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

ENG3202 – Computer

Programming
Lecture 5
By: Dr. Raja Kamil

Learning Outcome
vUnderstanding and apply conditional statement
switch…case
Recall Quiz
Generate or construct pseudocode, flowchart and codes for the
output below. Use if…else to decide which value is the smallest
and largest
A Solution
Quiz
Consider the following pseudocode, then generate a flowchart and
code.

Set a variable to be numerical value between 1 to 4


If the variable is equal to 1, then print the text ‘Choice is 1’
If the variable is equal to 2, then print the text ‘Choice is 2’
If the variable is equal to 3, then print the text ‘Choice is 3’
If the variable is equal to 4, then print the text ‘Choice is other than
1, 2, and 3’
switch…case
• An alternative to conditional statement if…else is to use
switch…case

x is the variable
containing the value
being considered

since x = 2 the flow control


will jump to case 2,
case 2 is executed.
‘Choice is 2’ will be printed
out
after executing case 1, program encounter the
default statement is …break
optional. Ok not to put it Breaks away from the loop/decision flow
switch…case flowchart
What is the output?
How does the flowchart
looks like?
What is the general format?

Case2
switch vs if

if switch
float Yes No
Relational operator Yes No
e.g. ‘=>‘

if (x => 2 && x < 4){


printf……
}
switch…case (char)
Determine the output.
Determine the printout

if the variable being considered doesn’t match


any of the cases, then the default will be
printed.
Determine the printout
(no break)

the control jump to case 2


case 2 is executed
no break to break the flow
all subsequent cases also executed
until break is found or program exits
the main
Determine the printout

case 5 is executed but yield nothing, no break is found.


case 6 is executed, print, break is found, exit program.
Determine the printout
(no break)

executed, no break found, continue


execute next case
executed, break found, break flow
exit switch

executed
Quiz: Generate the following

Design a program using switch…case


statement to output either of the following based
on arithmetic operation chosen by the user

3+2=5
3–2=1
3*2=6
3 / 2 =1.5
Quiz: Determine the output

In this program we are using a


floating-point number as an
expression so, we got the error

Floating-point as an expression is
not allowed in the switch case
Quiz: Determine the printout with ID
500 and password 000

This is a nested switch

You might also like