Lecture 5: Selection and
Iteration
Harbin Institute of Technology ( Shenzhen )
School of Computer Science and Technology
Zhang Meishan ([Link]@[Link])
Copyright : Harbin Institute of Technology , Su Xiaohong , sxh@[Link]
Overview
• Relational Operators
• Logical Operators
• Selection
• Iteration
Background
• Sequence program construct
• Top-to-bottom: execute one statement after the other
• Only the simplest of problems can be solved
statement 1
…
sequence construct
statement i
…
statement n
Background
• Selection and iteration program constructs
statement 1
statement 2
…
True
statement i+1 statement i selection construct
False
statement i+2
…
statement n
Background
• Selection and iteration program constructs
statement 1
statement 2
…
True iteration construct
statement i+1 statement i
False
statement i+2
…
statement n
5.1 Relational Operator
• Relational operator
5.1 Relational Operator
• Precedence
high arithmetic operation
relational operation >, <, >=, <=
relational operation ==, !=
...
low assignment operation
Combination order: left to right
5.1 Relational Operator
• Equivalence in judgement: use ==, not =
Output: 0(False) Output: 2
5.1 Relational Operator
• Continuous use of relational characters may not yield the results
you need!
Output:
•Due to the left-to-right associativity of relational
operators, the expression 1 < b is evaluated first,
resulting in a boolean value, either 0 or 1.
•Both 0 and 1 are less than 3, so regardless of the
value of b, the output result will be 1.
5.2 Logical Operators
• precedence
• && (AND) and || (OR) joins two simple conditions.
• &&: The result is only true when both simple conditions are true.
• ||: The result is true if either or both are true.
• ! (NOT) : reverse a given condition
• If the result is true, then it becomes false,
• If it is false, then it becomes true.
5.2 Logical Operators
• Logical operators
Symbol Description
&& AND: both are true
|| OR : one of the two is
true
! a NOTb a && b a || b !a !b
0 0 0 0 1 1
0 1 0 1 1 0
1 0 0 1 0 1
1 1 1 1 0 0
5.2 Logical Operators
• Logical operators
5.2 Logical Operators
• Logical operators
1.i > j > k
* It's legal in C++, but it's probably not what you expect it to say
* Equivalent to (i > j) > k, does not test whether j is between i and k
* Different from (i > j) && (j > k)
[Link] ‘ch’ is an uppercase English letter
'Z' >= ch >= 'A' false
(ch >= 'A') && (ch <= 'Z')
[Link] CH is a numeric character
(ch >= '0') && (ch <= '9’)
5.3 Selection
• The if statement
• starts with the keyword if followed by an expression in parentheses
•If the expression is true, then the statement following the if is executed.
•If the expression is untrue, then the statement following the if is not executed.
5.3 Selection
• The if statement
• If you want to include more than a single statement to be
executed when the condition is fulfilled, these statements shall
be enclosed in braces ({}), forming a block:
•As usual, indentation and line breaks in the code
have no effect, so the above code is equivalent to:
5.3 Selection
• The if statement
• starts with the keyword if followed by an expression in parentheses
• relational operator
5.3 Selection
• The if statement
step
stepaa
(condition is
ifif(condition is
true)
true)
{{
step
stepmm
step
stepnn
}}
step
stepbb
5.3 Selection
• The if statement
Running Results
5.3 Selection
• The if-else statement
• With an if-else there is choice of executing one or other of two
statements.
if ( expression )
true
false
statement 1
else
statement 2
statement …
5.3 Selection
• The if-else statement
• Selection statements with if can also specify what happens when the
condition is not fulfilled, by using the else keyword to introduce an
alternative statement. Its syntax is:
where statement1 is executed in case condition is true, and in case it
is not, statement2 is executed.
5.3 Selection
• The if-else statement
Step
Stepaa
(condition is
ifif(condition is
true)
true)
{{
Step
Stepmm
Step n
Step n
}}
else
else
{{
Step
Stepxx
Step
Stepyy
}}
Step
Stepzz
5.3 Selection
• The if-else statement
• This prints x is 100, if indeed x has a value of 100; but if it does
not, and only if it does not, it prints x is not 100 instead.
5.3 Selection
• The if-else statement
• Several if + else structures can be concatenated with the intention of checking a
range of values. For example:
• This prints whether x is positive, negative, or zero by concatenating two if-else
structures.
• Again, it would have also been possible to execute more than a single statement
per case by grouping them into blocks enclosed in braces: {}.
5.3 Selection
• Program Example
•Ifthe value of account_balance is
less than 0,line 16 is executed;
•Otherwise the line 19 is executed.
5.3 Selection
• Compound statements : A
compound statement is one or
more statements enclosed in
braces { and }.
Running Results
The statements within a compound
statement are usually indented for
appearance purposes.
5.3 Selection
• Nested if statements
• When an if statement occurs within another if statement 。
5.3 Selection
• switch statement
• equivalent to a series of if-else statements
• keyword : switch, case
5.3 Selection
• Switch statement
“op” must be of type char or int.
1 The value of “ op” is compared with
each “case” value in turn
2 Statements following “case” will be
executed if matched
3 “break” statement terminates the
switch statement.
5.3 Selection
• Switch statement
If no case matches the value of “OP”,
the default case is executed
5.3 Selection
• The conditional operator ?:
• a short form of if-else.
5.4 Iteration
• iterative control statements
• the while statement
• the do-while statement while (expression)
• the for statement
if value of the expression is true
• The while statement
{
statement 1;
otherwise
…
statement n;
}
other statements;
5.4 Iteration
• The while statement
• The while-loop simply repeats statement while expression is true. If,
after any execution of statement, expression is no longer true, the
loop ends, and the program continues right after the loop.
5.4 Iteration
• The while statement
5.4 Iteration
The sequence in a while loop:
1. Evaluate the control expression.
2. If the control expression is true, execute
the statements in the loop and go back to 1.
3. If the control expression is false, exit the
loop and execute the next statement after
the loop.
• The statements 16~19 enclosed within { } are executed repeatedly if
the control expression “num != 0” is true.
• The repeated execution statements is called a program loop.
5.4 Iteration
• Program Example: Factorial calculation
factorial *= i
equals to
factorial = factorial *i
5.4 Iteration
the statements in a do-while loop
are executed at least once
• The do-while loop
• 1. Execute the statements in the loop.
do
• 2. Evaluate the control expression.
• 3. If the control expression is true
then go back to 1. {
• 4. If the control expression is false statement 1;
then exit the loop and execute the if value of the
… expression is true
next statement after the loop.
statement n;
}
It behaves like a while-loop, except that condition is
evaluated after the execution of statement instead of while (expression)
before, guaranteeing at least one execution of
statement, even if condition is never fulfilled. otherwise
other statements;
5.4 Iteration
• The do-while statement
5.4 Iteration
• The for statement
• initial expression; for(“initial”; ”continue”; ”increment”)
• executed once at the beginning of the
loop if value of “continue” is
• continue condition; otherwise true
• loop continues while the it is true;
• loop terminates when it becomes false;
• increment expression {
• executed at the end of every pass
statement 1;
through the loop
…
statement n;
}
other statements;
5.4 Iteration
• The for statement
• The for loop is designed to iterate a number of times. Its syntax is:
• Like the while-loop, this loop repeats statement while condition is true.
• But, in addition, the for loop provides specific locations to contain an initialization
and an increase expression, executed before the loop begins the first time, and
after each iteration, respectively.
• Therefore, it is especially useful to use counter variables as condition.
5.4 Iteration
• Program Example
Running Results
The statements 13~17 enclosed
within { } are executed 5 times
{ } is used to clearly show the body of
the loop.
5.4 Iteration
• The for statement
• It works in the following way:
[Link] is executed. Generally, this declares a counter variable, and sets it
to some initial value. This is executed a single time, at the beginning of the loop.
[Link] is checked. If it is true, the loop continues; otherwise, the loop ends,
and statement is skipped, going directly to step 5.
[Link] is executed. As usual, it can be either a single statement or a block
enclosed in curly braces { }.
[Link] is executed, and the loop gets back to step 2.
[Link] loop ends: execution continues by the next statement after it.
5.4 Iteration
• Some specific features
• variable i could also be defined before the for statement
• i starts at 10 and is decremented at the end of each pass
• multiple expressions separated by commas in the for statement
• Any or all of the three expressions may be omitted from a for statement, ; must
always be present
for(;;) { ……} create an infinite loop because there is no condition to end the loop.
5.4 Iteration
• Program Example Running Results
The statements 11~13 enclosed
within { } are executed n times
Why should sum = 0 ?
5.4 Iteration
• Program Example: Factorial calculation
5.4 Iteration
Nested loops: When a loop is contained within another loop
•The outer loop (lines 26~35) starts with i at 1
• Line 28 displays a | at the left of the screen
•The inner loop (lines 29~32) is then executed with
j starting at 1 and ending when j exceeds 12.
•Each iteration of the inner loop displays a number
in the multiplication table.
•When the inner loop is completed, the outer loop
regains control, and i is incremented to 2.
5.4 Iteration
Nested loops: When a loop is contained within another loop
Running Results
Q&A
ZhangMei
Shan
47/37
Homework
• 1. Rewrite the following if-else using a switch statement:
Homework
• 2. In a triangle, the sum of any two sides must be greater
than the third side. Write a program to input three
numbers and determine if they form a valid triangle.
• 3. Rewrite the following using a for loop.
Homework
• 4. What is displayed when the following program is run
and the number 1234 is entered?
• 5. Write a program to find the sum of all the odd integers
in the range 1 to 99.
Homework
• 6. Write a program to display the following triangles:
Input the size of the triangles from the keyboard.