Introduction to Selection Statements in Programming

Module 3
Selection Statements
Reminder
We will use generic PRINT and READ statements
PRINT() and PRINTLINE() mean
System.out.print() and System.out.println() for Java
Console.Write() and Console.WriteLine() for C#
cout with and without the endl
READ() means
Scanner s = new Scanner (System.in); s.nextInt() for Java
Console.Read() for C#
cin or getline() for C++
M
o
t
i
v
a
t
i
o
n
In the programs we have written thus far, statements
are executed one after the other, in the order in
which they appear.
Programs often need 
more than one path
 of
execution, however.  Many algorithms require a
program to execute some statements only under
certain circumstances.  This can be accomplished
with decision structures.
T
o
p
i
c
s
1.
Fl
o
w
 
of Control
2.
Boolean
 
d
e
fi
n
iti
o
n
 & Conditional Statements
3.
Rel
a
ti
o
n
a
l Op
e
rat
o
rs
4.
Logical Operators
5.
Operator Precedence
6.
 
i
f
 
stat
e
m
e
nts
7.
 
if
-
e
l
se
 
stat
e
m
e
n
t
s
8.
 
if
-
else
-
if
 statements
9.
 
switch
 statements
1
.
 
 
F
l
o
w
 
o
f
 
C
o
n
t
r
o
l
The order of statement execution is called the 
flow of control
By default, execution is 
linear
: one statement after another
However, we can:
decide
 whether or not to execute a particular statement
execute a statement over and over, repetitively
These selection (decision) statements are 
based on 
boolean
expressions
 (or 
conditions
) that evaluate to 
true
 or 
false
A
 
F
l
o
w
 
D
i
a
g
r
a
m
2
.
 
T
h
e
 
B
o
o
l
e
a
n
A
 
Boo
lean
 
r
e
solves
 
to either 
true
 
or
 
fa
l
se
Y
ou
 
can 
g
et
 
Bo
o
le
a
n va
l
u
e
s sever
a
l d
i
f
f
e
re
n
t w
a
ys
Simple
Comp
l
ex
T
h
ese
 
Booleans
 
will
 
be 
u
sed
 
(l
a
t
e
r)
 
to
 m
ake
d
e
cisions
2
.
 
 
S
e
l
e
c
t
i
o
n
 
S
t
a
t
e
m
e
n
t
s
A 
Selection (conditional) statement
 allows us to choose
which statements will be executed next:
if
 – block of code executes if a Boolean expression is true.
 
if
-
else
will execute one block of code if the 
B
oolean
expression is 
true
, or another if it is 
false
.
if
-
else
-
if
tests a series of B
oolean expressions and
e
xecute corresponding block when it finds one that is 
true
.
switch 
lets the value of a variable determine where the
program will branch to.
3
.
 
R
e
l
a
t
i
o
n
a
l
 
O
p
e
r
a
t
o
r
s
Create a 
true
 or 
false
 using a relational operator:
 
>
 
 
gre
a
ter 
t
h
a
n
 
<
 
 
le
s
s
 
than
 
==
 
 
eq
u
als
.equals( ) method for strings
 
!= 
 
not eq
u
al
 
>=
 
 
gre
a
ter 
t
h
a
n
 
or eq
u
al
 
<=
 
 
less
 
than
 
or equal
N
o
t
e
 
t
h
e
 
d
i
f
f
e
r
e
n
c
e
 
b
e
t
w
e
e
n
 
t
h
e
 
e
q
u
a
l
i
t
y
 
o
p
e
r
a
t
o
r
 
(
=
=
)
 
a
n
d
 
t
h
e
a
s
s
i
g
n
m
e
n
t
 
o
p
e
r
a
t
o
r
 
(
=
)
R
e
l
a
t
i
o
n
a
l
 
O
p
e
r
a
t
o
r
s
 
E
x
a
m
p
l
e
Literal Example:
5 > 3
   
// true
6 != 6
   
// false
true
 == (4 <=2) 
 
// false
‘c’ != ‘b’
  
// true
Variable Example:
Num1 
= 
5
Num2 
= 
7
Result 
= N
um2 > Num1 
// Result is true
R
e
l
a
t
i
o
n
a
l
 
O
p
e
r
a
t
o
r
s
 
E
x
a
m
p
l
e
String equality – must use methods
string myString = "
red
";
string yourString = "
blue
";
Java:  myString.equals(yourString)  
// false
C#: myString.Equals(yourString)     
// false
// 0 if true, otherwise -1 or +1
// depending on which string is lower/higher
C++: myString.compare(yourString)
4
.
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
Boolean expressions can also use the following 
logical
operators
:
Logical NOT
Logical AND
Logical OR
They 
all take Boolean operands and produce Boolean results
Logical NOT is a unary operator (it operates on one operand)
Logical AND and OR are binary operators (each operates on
two operands)
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
(
N
O
T
)
The 
logical 
NOT
 operation is also called 
logical negation
 or
logical complement
If some Boolean condition 
a
 is 
true
, then 
NOT a
 is 
false
;
if 
a
 is 
false
, then 
NOT a
 is 
true
Logical expressions can be shown using a 
truth table
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
(
A
N
D
 
a
n
d
 
O
R
)
The 
logical 
AND
 expression
a 
AND
 b
 
is 
true
 if both 
a
 and 
b
 are 
true
, and 
false
 otherwise
The 
logical
 OR
 expression
a 
OR
 b
 
is 
true
 if either 
a
 or 
b
 is 
true
, or both are 
true
, and 
false
otherwise
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
i
n
 
B
o
o
l
e
a
n
 
E
x
p
r
e
s
s
i
o
n
s
Expressions can form complex conditions
 
IF
 ((total < (MAX + 5)) 
AND
 (
NOT
 found)) 
THEN
   PRINT ("Processing…")
 
ENDIF
Mathematical operators have 
higher precedence
 than the
Relational and Logical operators
Relational operators have 
higher precedence
 than Logical
operators
 
B
o
o
l
e
a
n
 
E
x
p
r
e
s
s
i
o
n
s
Specific expressions can be evaluated using truth tables
Given    
X = ((total < (MAX + 5)) 
AND 
(
NOT
 found))
   
What is the values of  
X
 
?
5
.
 
 
O
r
d
e
r
 
o
f
 
P
r
e
c
e
d
e
n
c
e
 
o
f
 
A
r
i
t
h
m
e
t
i
c
,
 
C
o
m
p
a
r
i
s
o
n
,
 
a
n
d
 
L
o
g
i
c
a
l
O
p
e
r
a
t
o
r
s
Source: http://www.bouraspage.com/repository/algorithmic-thinking/what-is-the-order-of-precedence-of-arithmetic-comparison-and-logical-operators
O
p
e
r
a
t
o
r
 
P
r
e
c
e
d
e
n
c
e
Applying operator precedence and associativity rule to the
expression:
  3 + 4 * 4 > 5 * (4 + 3) - 1
(1)
Inside parentheses first
(2)
Multiplications
(3)
Addition
(4)
Subtraction
(5)
Greater than
The expression resolves to 
FALSE
N
o
t
e
s
 
o
n
 
I
n
d
e
n
t
a
t
i
o
n
In Java, C# and C++
Makes no difference, but crucial for readability and debugging.
Code inside the 
IF
 statement is indented and should also be
enclosed in curly braces { }.
6
.
 
L
o
g
i
c
 
o
f
 
a
n
 
I
F
 
S
t
a
t
e
m
e
n
t
N
o
w
 
L
e
t
s
 
D
o
 
S
o
m
e
t
h
i
n
g
!
Using
 
t
h
e
 
IF
 
stat
e
m
e
n
t
,
 
we c
a
n
 
d
e
cide
whe
t
h
e
r
 
or
 
n
o
t to
 
execu
t
e
 
some
 
code
Has
 
f
o
rm
a
t:
   
IF
 
(
condition
) 
THEN
      
//
 
a
l
l 
t
he
 
co
d
e
 
th
a
t
s
 h
ere
 wi
ll
 
o
n
ly
 
e
xe
cu
t
e
      
//
 
IF
 
a
n
d
 o
nly
 IF
 
t
he
 
condition
 
a
bo
ve
 
is
 
t
r
ue
   
ENDIF
P
r
o
b
l
e
m
 
S
t
a
t
e
m
e
n
t
Write a program to convert user input of Celsius
temperature to Fahrenheit.  Display the converted
temperature to the user.  Issue a heat warning IF
temperature is at least 90 degrees Fahrenheit.
Fahrenheit = 9.0 / 5.0 * Celsius + 32
P
s
e
u
d
o
c
o
d
e
 
-
 
I
F
 
S
t
a
t
e
m
e
n
t
BEGIN MAIN
   CREATE Fahrenheit = 0, Celsius = 0
   PRINT 
“Enter Celsius temperature: ”
   READ user input
   Celsius = user input
   Fahrenheit = 9.0 / 5.0 * Celsius + 32
   PRINT Fahrenheit
   
IF
 (Fahrenheit >= 90) 
THEN
 
PRINT 
“heat warning”
   
ENDIF
END MAIN
E
x
a
m
p
l
e
 
-
 
i
f
 
S
t
a
t
e
m
e
n
t
      
double
 celsius= 0.0, fahrenheit = 0.0;
      PRINT (
“What is the Celsius temperature? "
);
      celsius = READ();
      fahrenheit = 9.0 / 5.0 * celsius + 32;
      PRINT (
“The temperature is "
 + fahrenheit +
         
“ degrees Fahrenheit”
);
      
if 
(fahrenheit >= 90) {
         PRINT(
“It is really hot out there!”
);
      }
P
s
e
u
d
o
c
o
d
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
O
R
BEGIN MAIN
   CREATE Fahrenheit = 0, Celsius = 0
  
 PRINT (
“What is the Celsius temperature? "
);
   Celsius = READ();
   Fahrenheit = 9.0 / 5.0 * Celsius + 32;
   PRINT Fahrenheit
   
IF
 ((Fahrenheit >= 90)  OR (Fahrenheit <= 20)) 
THEN
 
PRINT 
“Extreme weather warning!”
   
END IF
END MAIN
E
x
a
m
p
l
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
O
R
double
 fahrenheit = 0.0, celsius = 0.0;
PRINT(
“What is the Celsius temperature? "
);
celsius = 
READ();
Fahrenheit = 
9.0 / 5.0 * celsius + 32;
PRINTLINE(
“The temperature is "
 + fahrenheit +
          “ degrees Fahrenheit”
);
 
if
 ((fahrenheit >= 90) || (fahrenheit <= 20))
{
 
PRINTLINE(
“Extreme weather warning!”
);
}
E
x
p
r
e
s
s
i
o
n
s
 
t
h
a
t
 
d
o
n
t
 
w
o
r
k
(
i
n
 
m
o
s
t
 
l
a
n
g
u
a
g
e
s
)
BEGIN MAIN
   CREATE Fahrenheit = 0, Celsius = 0
  
 PRINT (
“What is the Celsius temperature? "
);
   Celsius = READ();
   Fahrenheit = 9.0 / 5.0 * Celsius + 32;
   PRINT Fahrenheit
   // THIS LINE BELOW
   
IF
 (20 <= Fahrenheit <= 90) 
THEN 
//BAD!
 
PRINT 
“It’s a pleasant day”
   
END IF
END MAIN
// Needs to be broken into two parts
P
s
e
u
d
o
c
o
d
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
N
O
T
BEGIN MAIN
   
CREATE Fahrenheit = 0, Celsius = 0
  
 PRINT (
“What is the Celsius temperature? "
);
   Celsius = READ();
   Fahrenheit = 9.0 / 5.0 * Celsius + 32;
   PRINT Fahrenheit
   
IF
 ( NOT (Fahrenheit >= 90) ) 
THEN
 
PRINT 
“It’s not hot!”
   
END IF
END MAIN
E
x
a
m
p
l
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
N
O
T
double
 fahrenheit = 0.0, celsius = 0.0;
PRINT(
“What is the Celsius temperature? "
);
celsius = 
READ();
Fahrenheit = 
9.0 / 5.0 * celsius + 32;
PRINT (
“The temperature is "
 + fahrenheit +
       “ degrees Fahrenheit”
);
 
if
 ( !(fahrenheit >= 90) )
{
 
PRINTLINE(
“It’s not hot out there!”
);
}
7
.
 
 
S
t
r
u
c
t
u
r
e
 
o
f
 
a
n
 
I
F
-
E
L
S
E
 
S
t
a
t
e
m
e
n
t
IF
 has a counterpart – the 
ELSE
 statement
Has format:
IF
 
(
condition) 
THEN
   
statementBlock that executes if condition is true
ELSE
   
statementBlock that executes if condition is
false
ENDIF
IF the condition is true, statementBlock1 is executed;  IF the condition
is false, statementBlock2 is executed
Notice there is no condition after the ELSE statement.
One or the other will be executed, 
but not both
7
.
 
L
o
g
i
c
 
o
f
 
a
n
 
I
F
-
E
L
S
E
 
s
t
a
t
e
m
e
n
t
P
r
o
b
l
e
m
 
R
e
d
e
f
i
n
e
d
Original Problem Statement: Write a program to convert user
input of Celsius temperature to Fahrenheit.  Display the
converted temperature to the user.  Issue a heat warning IF
temperature is at least 90 degrees Fahrenheit.
Add: 
IF the temperature is not that high, output a message to
the user.
P
s
e
u
d
o
c
o
d
e
 
 
I
F
-
E
L
S
E
 
S
t
a
t
e
m
e
n
t
BEGIN MAIN
  CREATE Fahrenheit = 0, Celsius = 0
  PRINT “Enter Celsius temperature: ”
  READ user input
  Celsius = user input
  Fahrenheit = 
9.0 / 5.0 * Celsius + 32
  PRINT Fahrenheit
  
IF
 (Fahrenheit >= 90) 
THEN
 
PRINT 
“heat warning”
  ELSE
 
PRINT 
“there is no extreme heat”
  ENDIF
END MAIN
E
x
a
m
p
l
e
 
 
i
f
-
e
l
s
e
(
C
o
d
e
 
S
n
i
p
p
e
t
)
double
 celsius = 0.0, fahrenheit = 0.0;
PRINT(
"What is the Celsius temperature? "
);
celsius = READ();
fahrenheit = 9.0 / 5.0 * celsius + 32;
PRINT(
"The temperature is "
 + fahrenheit + 
" degrees Fahrenheit"
);
if
 (fahrenheit >= 90)
{
    PRINT(
"It is really hot out there, be careful!"
);
}
else
{
    PRINT(
“There is no extreme heat today.”
);
}
P
s
e
u
d
o
c
o
d
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
A
N
D
BEGIN MAIN
  CREATE Fahrenheit = 0
  PRINT 
“Enter Fahrenheit temperature: ”
  Fahrenheit = READ
  PRINT Fahrenheit
 
IF
 ((Fahrenheit >= 50) AND (Fahrenheit <= 80)) 
THEN
  
PRINT 
“It’s a pretty good day!”
 
ELSE
  
PRINT 
“It may be better to stay inside.”
 
END IF
END MAIN
E
x
a
m
p
l
e
 
 
L
o
g
i
c
a
l
 
O
p
e
r
a
t
o
r
s
 
-
 
A
N
D
double
 fahrenheit = 0.0;
PRINT ("
What is the Fahrenheit temperature?
”);
READ (fahrenheit);
if
 ((fahrenheit >= 50) && (fahrenheit <= 80)) {
   PRINTLINE (
"It’s a pretty good day!"
);
}
else
{
   PRINTLINE (
"It may be better to stay inside."
);
}
8
.
 
S
t
r
u
c
t
u
r
e
 
o
f
 
a
n
 
I
F
-
E
L
S
E
-
I
F
S
electing
 
one
 
from
 
many
A
s soon
 
as
 
one
 
is
 
true,
 
the
 
re
s
t
 
are
 
not
 
con
s
idered
Has
 
format:
IF
 (condition) 
THEN
   //statementBlock that executes if the above boolean is true
ELSE IF
 
(condition) 
THEN
   //statementBlock that executes if the above boolean is true
ELSE IF
 
(condition) 
THEN
   //statementBlock that executes if the above boolean is true
ELSE
   //statementBlock that executes if the 
nothing
 matched above
ENDIF
Note: only one set of statements will ever
execute. Trailing else is optional
8
.
 
L
o
g
i
c
 
o
f
 
a
n
 
I
F
-
E
L
S
E
-
I
F
P
r
o
b
l
e
m
 
R
e
d
e
f
i
n
e
d
Original Problem Statement: Write a program to convert user
input of Celsius temperature to Fahrenheit.  Display the
converted temperature to the user.  Issue a heat warning if
temperature is at least 90 degrees Fahrenheit.
Add: 
two additional messages to recommend an action based
on temperature (in the 70’s or in the 80’s), and a trailing else.
P
s
e
u
d
o
c
o
d
e
 
 
I
F
-
E
L
S
E
-
I
F
BEGIN MAIN
  CREATE Fahrenheit = 0, Celsius = 0
  PRINT 
“Enter Celsius temperature: ”
  READ user input
  Celsius = user input
  Fahrenheit = 
9.0 / 5.0 * Celsius + 32
  PRINT Fahrenheit
  
IF
 (Fahrenheit >= 90) 
THEN
 
PRINT 
“heat warning”
  ELSE IF
 (Fahrenheit >= 80) 
THEN
 
PRINT 
“it is warm, but there is no extreme heat”
  ELSE IF
 (Fahrenheit >= 70) 
THEN
 
PRINT 
“the temperature is pleasant and suggest a picnic”
  ELSE
 
PRINT 
“a suggestion to take a jacket”
  END IF
END MAIN
P
s
e
u
d
o
c
o
d
e
 
 
I
F
-
E
L
S
E
-
I
F
 
 
B
A
D
 
V
E
R
S
I
O
N
BEGIN MAIN
  CREATE Fahrenheit = 0, Celsius = 0
  PRINT 
“Enter Celsius temperature: ”
  READ user input
  Celsius = user input
  Fahrenheit = 
9.0 / 5.0 * Celsius + 32
  PRINT Fahrenheit
  
IF
 (Fahrenheit >= 70) 
THEN
 
PRINT 
“the temperature is pleasant and suggest a picnic”
  ELSE IF
 (Fahrenheit >= 80) 
THEN
 
PRINT 
“it is warm, but there is no extreme heat”
  ELSE IF
 (Fahrenheit >= 90) 
THEN
 
PRINT 
“heat warning”
  ELSE
 
PRINT 
“a suggestion to take a jacket”
  END IF
END MAIN
Why is this bad?
E
x
a
m
p
l
e
 
 
i
f
-
e
l
s
e
-
i
f
double
 celsius = 0.0, fahrenheit = 0.0;
PRINT(
"What is the Celsius temperature? "
);
celsius = READ();
fahrenheit = 9.0 / 5.0 * celsius + 32;
PRINT(
"The temperature is "
 + fahrenheit +
      "degrees Fahrenheit"
);
if 
(fahrenheit >= 90) {
 
PRINT(
“It is really hot!”
);
}
else if
 (fahrenheit >= 80) {
 
PRINT(
“It is very warm!”
);
}
else if
 (fahrenheit >= 70) {
 
PRINT(
“It is very pleasant!”
)
}
else 
{
 
PRINT(
“It is cool today”
);
}
9
.
 
 
T
h
e
 
s
w
i
t
c
h
 
S
t
a
t
e
m
e
n
t
The 
switch statement
 provides another way to decide which
statement to execute next
The switch statement uses a 
variable
 and attempts to match
the value to one of 
several possible 
cases (cases)
Each case contains a value and a list of statements
The flow of control transfers to statement associated with
the 
first case value that matches
9
.
 
S
t
r
u
c
t
u
r
e
 
o
f
 
a
 
s
w
i
t
c
h
The general syntax of a 
switch
 statement is:
SWITCH
 (
variable)
BEGIN
  
CASE
 1:
       
statementBlock
       
break
 
// SUPER IMPORTANT BREAKS!
 
  
CASE
 2:
       
statementBlock
       
break 
 
// If we don’t include breaks, it goes to next condition
  
CASE
 3:
       statementBlock
       
break
  
CASE
 
...
  DEFAULT:
       
statementBlock
ENDSWITCH
7. Logic of 
switch
 statement
break
 Statement
Often a 
break
 
statement is used as the last statement in
each case's statement list
break statements are 
required
 in C#
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
Sometimes this may be appropriate, but often not…
D
e
f
a
u
l
t
 
C
a
s
e
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 the
default case 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
statement
S
w
i
t
c
h
 
S
t
a
t
e
m
e
n
t
 
E
x
p
r
e
s
s
i
o
n
The variable of a 
switch
 statement must be an 
integer type
(
byte
, 
short
, 
int
, 
long
) or a 
char
 type.
It cannot be a 
boolean
 value or a floating point value
(
float
 or 
double
)
You cannot perform relational checks with a 
switch
statement
In Java and C#, you can also switch on a string
P
r
o
b
l
e
m
 
R
e
d
e
f
i
n
e
d
Original Problem Statement: Write a program to convert user
input of Celsius temperature to Fahrenheit.  Display the
converted temperature to the user.
Add: 
Using the Fahrenheit temperature and division,
determine the conditions outside (i.e., in the 100’s, 90’s, etc.).
Use a switch statement to recommend user action based on
the result.  If it is in the 60’s or below, suggest the user take a
jacket.
P
s
e
u
d
o
c
o
d
e
 
 
s
w
i
t
c
h
 
S
t
a
t
e
m
e
n
t
// Read user input like before
conditions = compute using Fahrenheit variable / 10
PRINTLINE("It is in the " + conditions + "0's.")
SWITCH
 (conditions) 
 
 
   
CASE
 10:
 
PRINT 
“stay inside”
, 
BREAK
 
   
CASE
 9
 
:
 
PRINT 
“be careful due to heat”
, 
BREAK
 
   
CASE
 8
 
:
 
PRINT 
“it is hot, but not extreme”
, 
BREAK
 
   
CASE
 7
 
:
 
PRINT 
“pack a picnic”
, 
BREAK
 
   
DEFAULT
:
 
PRINT 
“take a jacket”
, 
BREAK
ENDCASE
s
w
i
t
c
h
 
E
x
a
m
p
l
e
int
 conditions = (
int
)fahrenheit / 10;
PRINTLINE(
"It is in the "
 + conditions + 
"0's."
);
switch
 (conditions)
{
 
case
 10:
       
 
 PRINT(
"It’s hot!  Stay inside!"
);
           
break
;
       
case
 9:
           PRINT(
"It is really hot out there!"
);
           
break
;
       
case
 8:
           PRINT(
"It is warm, but no extreme heat!"
);
           
break
;
       
case
 7:
           PRINT(
"It is very pleasant today!"
);
           
break
;
       
default
:
           PRINT(
"Take a jacket!"
);
           
break
;
}
S
u
m
m
a
r
y
 Bo
o
l
e
an
 
val
u
es
 
can
 
be
 
g
e
n
er
a
t
e
d several
 
ways
 Use
 
the
 
i
f
 
stat
e
m
e
nt
 
to
 
d
e
cide
 
which p
a
th
 
to
 
t
a
ke
 Use
 
the
 
else
 
to
 
take
 
the
 
a
l
ter
n
ate
 
p
a
th
 The
 
if
-
els
e
-
i
f
 
stat
e
m
e
nts
 
al
l
ow f
o
r selecti
n
g
 
o
n
e
f
rom
 
m
a
ny
 Use the 
switch
 statement to allow a variable to
determine program path
Slide Note
Embed
Share

Selection statements in programming allow for executing specific blocks of code based on certain conditions. They provide a way to control the flow of a program by evaluating Boolean expressions. The use of if, if-else, if-else-if, and switch statements enables programmers to create multiple paths of execution and make decisions within their code.

  • Selection Statements
  • Programming Basics
  • Decision Making
  • Conditional Logic

Uploaded on Apr 19, 2024 | 5 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Module 3 Selection Statements

  2. Reminder We will use generic PRINT and READ statements PRINT() and PRINTLINE() mean System.out.print() and System.out.println() for Java Console.Write() and Console.WriteLine() for C# cout with and without the endl READ() means Scanner s = new Scanner (System.in); s.nextInt() for Java Console.Read() for C# cin or getline() for C++

  3. Motivation Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often need more than one path of execution, however. Many algorithms require a program to execute some statements only under certain circumstances. This can be accomplished with decision structures.

  4. T T opics opics 1. 2. 3. 4. 5. 6. if statements 7. if-else statements 8. if-else-if statements 9. switch statements Flow of Control Boolean definition & Conditional Statements Relational Operators Logical Operators Operator Precedence

  5. 1. Flow of Control 1. Flow of Control The order of statement execution is called the flow of control By default, execution is linear: one statement after another However, we can: decide whether or not to execute a particular statement execute a statement over and over, repetitively These selection (decision) statements are based on boolean expressions (or conditions) that evaluate to true or false

  6. A Flow Diagram A Flow Diagram

  7. 2. 2. The Boolean The Boolean A Boolean resolves to either true or false You can get Boolean values several different ways Simple Complex These Booleans will be used (later) to make decisions

  8. 2. Selection Statements 2. Selection Statements A Selection (conditional) statement allows us to choose which statements will be executed next: if block of code executes if a Boolean expression is true. if-else will execute one block of code if the Boolean expression is true, or another if it is false. if-else-if tests a series of Boolean expressions and execute corresponding block when it finds one that is true. switch lets the value of a variable determine where the program will branch to.

  9. 3. Relational Operators 3. Relational Operators Create a true or false using a relational operator: > < == .equals( ) method for strings != not equal >= greater than or equal <= less than or equal greater than less than equals Note the difference between the equality operator (==) and the assignment operator (=)

  10. Relational Operators Example Relational Operators Example Literal Example: 5 > 3 6 != 6 true == (4 <=2) // false c != b // true // false // true Variable Example: Num1 = 5 Num2 = 7 Result = Num2 > Num1 // Result is true

  11. Relational Operators Example Relational Operators Example String equality must use methods string myString = "red"; string yourString = "blue"; Java: myString.equals(yourString) // false C#: myString.Equals(yourString) // false // 0 if true, otherwise -1 or +1 // depending on which string is lower/higher C++: myString.compare(yourString)

  12. 4. Logical Operators 4. Logical Operators Boolean expressions can also use the following logical operators: Logical NOT Logical AND Logical OR They all take Boolean operands and produce Boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and OR are binary operators (each operates on two operands)

  13. Logical Operators (NOT) Logical Operators (NOT) The logical NOT operation is also called logical negation or logical complement If some Boolean condition a is true, then NOT a is false; if a is false, then NOT a is true Logical expressions can be shown using a truth table

  14. Logical Operators (AND and OR) Logical Operators (AND and OR) The logical AND expression a AND b is true if both a and b are true, and false otherwise The logical OR expression a OR b is true if either a or b is true, or both are true, and false otherwise

  15. Logical Operators Logical Operators

  16. Logical Operators in Boolean Expressions Logical Operators in Boolean Expressions Expressions can form complex conditions IF ((total < (MAX + 5)) AND (NOT found)) THEN PRINT ("Processing ") ENDIF Mathematical operators have higher precedence than the Relational and Logical operators Relational operators have higher precedence than Logical operators

  17. Boolean Expressions Boolean Expressions Specific expressions can be evaluated using truth tables Given X = ((total < (MAX + 5)) AND (NOT found)) What is the values of X?

  18. 5. Order of Precedence of Arithmetic, Comparison, and Logical 5. Order of Precedence of Arithmetic, Comparison, and Logical Operators Operators Source: http://www.bouraspage.com/repository/algorithmic-thinking/what-is-the-order-of-precedence-of-arithmetic-comparison-and-logical-operators

  19. Operator Precedence Operator Precedence Applying operator precedence and associativity rule to the expression: 3 + 4 * 4 > 5 * (4 + 3) - 1 (1) Inside parentheses first (2) Multiplications (3) Addition (4) Subtraction (5) Greater than The expression resolves to FALSE

  20. Notes on Indentation Notes on Indentation In Java, C# and C++ Makes no difference, but crucial for readability and debugging. Code inside the IF statement is indented and should also be enclosed in curly braces { }.

  21. 6. Logic of an 6. Logic of an IF IF Statement Statement

  22. Now L Now Le et t s Do Someth s Do Somethi ing! ng! Using the IF statement, we can decide whether or not to execute some code Has format: IF (condition) THEN // all the code that s here will only execute // IF and only IF the condition above is true ENDIF

  23. Problem Statement Problem Statement Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning IF temperature is at least 90 degrees Fahrenheit. Fahrenheit = 9.0 / 5.0 * Celsius + 32

  24. Pseudocode Pseudocode - - IF IF Statement Statement BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT Enter Celsius temperature: READ user input Celsius = user input Fahrenheit = 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit >= 90) THEN PRINT heat warning ENDIF Ps END MAIN

  25. Example Example - - if if Statement Statement double celsius= 0.0, fahrenheit = 0.0; PRINT ( What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT ( The temperature is " + fahrenheit + degrees Fahrenheit ); if (fahrenheit >= 90) { PRINT( It is really hot out there! ); }

  26. Pseudocode Pseudocode Logical Operators Logical Operators - - OR OR BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT ( What is the Celsius temperature? "); Celsius = READ(); Fahrenheit = 9.0 / 5.0 * Celsius + 32; PRINT Fahrenheit IF ((Fahrenheit >= 90) OR (Fahrenheit <= 20)) THEN PRINT Extreme weather warning! END IF END MAIN Ps

  27. Example Example Logical Operators Logical Operators - - OR OR double fahrenheit = 0.0, celsius = 0.0; PRINT( What is the Celsius temperature? "); celsius = READ(); Fahrenheit = 9.0 / 5.0 * celsius + 32; PRINTLINE( The temperature is " + fahrenheit + degrees Fahrenheit ); if ((fahrenheit >= 90) || (fahrenheit <= 20)) { PRINTLINE( Extreme weather warning! ); }

  28. Expressions that dont work Expressions that don t work (in most languages) (in most languages) BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT ( What is the Celsius temperature? "); Celsius = READ(); Fahrenheit = 9.0 / 5.0 * Celsius + 32; PRINT Fahrenheit // THIS LINE BELOW IF (20 <= Fahrenheit <= 90) THEN //BAD! PRINT It s a pleasant day END IF END MAIN Ps // Needs to be broken into two parts

  29. Pseudocode Pseudocode Logical Operators Logical Operators - - NOT NOT BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT ( What is the Celsius temperature? "); Celsius = READ(); Fahrenheit = 9.0 / 5.0 * Celsius + 32; PRINT Fahrenheit IF ( NOT (Fahrenheit >= 90) ) THEN PRINT It s not hot! END IF END MAIN Ps

  30. Example Example Logical Operators Logical Operators - - NOT NOT double fahrenheit = 0.0, celsius = 0.0; PRINT( What is the Celsius temperature? "); celsius = READ(); Fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT ( The temperature is " + fahrenheit + degrees Fahrenheit ); if ( !(fahrenheit >= 90) ) { PRINTLINE( It s not hot out there! ); }

  31. 7. Structure of an 7. Structure of an IF IF- -ELSE ELSE Statement Statement IF has a counterpart the ELSE statement Has format: IF (condition) THEN statementBlock that executes if condition is true ELSE statementBlock that executes if condition is false ENDIF IF the condition is true, statementBlock1 is executed; IF the condition is false, statementBlock2 is executed Notice there is no condition after the ELSE statement. One or the other will be executed, but not both

  32. 7. Logic of an 7. Logic of an IF IF- -ELSE ELSE statement statement

  33. Problem Redefined Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning IF temperature is at least 90 degrees Fahrenheit. Add: IF the temperature is not that high, output a message to the user.

  34. Pseudocode Pseudocode IF IF- -ELSE ELSE Statement Statement BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT Enter Celsius temperature: READ user input Celsius = user input Fahrenheit = 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit >= 90) THEN PRINT heat warning ELSE PRINT there is no extreme heat ENDIF END MAIN Ps

  35. Example Example if if- -else (Code Snippet) (Code Snippet) else double celsius = 0.0, fahrenheit = 0.0; PRINT("What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT("The temperature is " + fahrenheit + " degrees Fahrenheit"); if (fahrenheit >= 90) { PRINT("It is really hot out there, be careful!"); } else { PRINT( There is no extreme heat today. ); }

  36. Pseudocode Pseudocode Logical Operators Logical Operators - - AND AND BEGIN MAIN CREATE Fahrenheit = 0 PRINT Enter Fahrenheit temperature: Fahrenheit = READ PRINT Fahrenheit END MAIN IF ((Fahrenheit >= 50) AND (Fahrenheit <= 80)) THEN PRINT It s a pretty good day! ELSE PRINT It may be better to stay inside. END IF Ps

  37. Example Example Logical Operators Logical Operators - - AND AND double fahrenheit = 0.0; PRINT ("What is the Fahrenheit temperature? ); READ (fahrenheit); if ((fahrenheit >= 50) && (fahrenheit <= 80)) { PRINTLINE ("It s a pretty good day!"); } else{ PRINTLINE ("It may be better to stay inside."); }

  38. 8. Structure of an 8. Structure of an IF IF- -ELSE ELSE- -IF IF Selecting one from many As soon as one is true, the rest are not considered Has format: IF (condition) THEN //statementBlock that executes if the above boolean is true ELSE IF (condition) THEN //statementBlock that executes if the above boolean is true ELSE IF (condition) THEN //statementBlock that executes if the above boolean is true ELSE //statementBlock that executes if the nothing matched above ENDIF Note: only one set of statements will ever execute. Trailing else is optional

  39. 8. Logic of an 8. Logic of an IF IF- -ELSE ELSE- -IF IF

  40. Problem Redefined Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning if temperature is at least 90 degrees Fahrenheit. Add: two additional messages to recommend an action based on temperature (in the 70 s or in the 80 s), and a trailing else.

  41. Pseudocode Pseudocode IF IF- -ELSE ELSE- -IF IF BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT Enter Celsius temperature: READ user input Celsius = user input Fahrenheit = 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit >= 90) THEN PRINT heat warning ELSE IF (Fahrenheit >= 80) THEN PRINT it is warm, but there is no extreme heat ELSE IF (Fahrenheit >= 70) THEN PRINT the temperature is pleasant and suggest a picnic ELSE PRINT a suggestion to take a jacket END IF END MAIN Ps

  42. Pseudocode Pseudocode IF IF- -ELSE ELSE- -IF IF BAD VERSION BAD VERSION BEGIN MAIN CREATE Fahrenheit = 0, Celsius = 0 PRINT Enter Celsius temperature: READ user input Celsius = user input Fahrenheit = 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit >= 70) THEN PRINT the temperature is pleasant and suggest a picnic ELSE IF (Fahrenheit >= 80) THEN PRINT it is warm, but there is no extreme heat ELSE IF (Fahrenheit >= 90) THEN PRINT heat warning ELSE PRINT a suggestion to take a jacket END IF END MAIN Why is this bad? Ps

  43. Example Example if if- -else else- -if if double celsius = 0.0, fahrenheit = 0.0; PRINT("What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT("The temperature is " + fahrenheit + "degrees Fahrenheit"); if (fahrenheit >= 90) { PRINT( It is really hot! ); } else if (fahrenheit >= 80) { PRINT( It is very warm! ); } else if (fahrenheit >= 70) { PRINT( It is very pleasant! ) } else { PRINT( It is cool today ); }

  44. 9. The 9. The switch switch Statement Statement The switch statement provides another way to decide which statement to execute next The switch statement uses a variable and attempts to match the value to one of several possible cases (cases) Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches

  45. 9. Structure of a 9. Structure of a switch switch The general syntax of a switch statement is: SWITCH (variable) BEGIN CASE 1: statementBlock break // SUPER IMPORTANT BREAKS! CASE 2: statementBlock break // If we don t include breaks, it goes to next condition CASE 3: statementBlock break CASE ... DEFAULT: statementBlock ENDSWITCH

  46. 7. Logic of switch statement

  47. break Statement Often a breakstatement is used as the last statement in each case's statement list break statements are required in C# A break statement causes control to transfer to the end of the switchstatement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often not

  48. Default Case Default Case 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 the default case 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 statement

  49. Switch Switch Statement Expression Statement Expression The variable of a switch statement must be an integer type (byte, short, int, long) or a char type. It cannot be a boolean value or a floating point value (float or double) You cannot perform relational checks with a switch statement In Java and C#, you can also switch on a string

  50. Problem Redefined Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Add: Using the Fahrenheit temperature and division, determine the conditions outside (i.e., in the 100 s, 90 s, etc.). Use a switch statement to recommend user action based on the result. If it is in the 60 s or below, suggest the user take a jacket.

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#