Basic Control Flow: Repetitions and Loop Statements: TCB2073 Structured Programming & Database Systems
Basic Control Flow: Repetitions and Loop Statements: TCB2073 Structured Programming & Database Systems
Statements
TCB2073
Structured Programming & Database
Systems
Objectives
By the end of this lecture, you will be able to:
describe the C++ repetition structures (while, for,
do..while)
design and implement a C++ program that involves
repetition structures
use SENTINEL in a do .. while statement
Page 2 of 13
Control Structures Revisit
Sequence Selection Repetition
Page 3 of 13
C++ Repetition Structures
Page 4 of 13
Terms
loop a control structure that repeats a group of steps in
a program.
loop body the statements that are repeated in the loop.
counter-controlled loop (counting loop) a loop whose
required number of iterations can be determined before
loop execution begins
loop repetition condition the condition that controls loop
repetition
loop control variable the variable whose value controls
loop repetition
infinite loop a loop that executes forever
Page 5 of 13
General Flowchart for while Statement
(counter-controlled loop)
initialisation
testing
Loop body
updating
Page 6 of 13
While Statement Syntax
Page 7 of 13
Problem 1: Print N (qty) asterisks
Page 8 of 13
Problem 2: Descending order (N to 0)
Page 9 of 13
Problem 3: Sum a series of N numbers
Page 10 of 13
Problem 4: Find the average of a series of N
numbers
Page 11 of 13
do .. while statement
executes the statements in the loop body at least once
Loop body
updating
testing
Page 12 of 15
do .. while statement syntax
SYNTAX: do {
statement
} while(loop repetition condition);
Page 13 of 15
Problem 1: Print N (qty) asterisks
start
counter = 0
Get qty
Display *
counter ++
F T
Counter < qty ?
Page 14 of 15
do .. while Counting Stars
Page 15 of 15
Problem 3: to sum N numbers,
without knowing N
updating
testing
Page 16 of 15
SENTINEL
Sentinel value an end marker that follows the last item
in a list of data
e.g
List of data:
56 90 85 100 72 45 999
Sentinel value
Page 17 of 15
for Statement Syntax
Page 18 of 15
Problem 2: Descending order (N to 0)
intialisation
testing
updating
Page 20 of 13
NESTED LOOP
The inner loop must be completely reside inside the outer
loop with a different control variable
Some possible structures of Nested For:
For I For I
For J
For J
For K
End J
For K
End K
End J
End K
End I End I
Page 21 of 13
Example
Page 22 of 13
Trace the output
Page 23 of 13
Class Average
Page 24 of 13
Digital Clock
Output:
00:00:00
00:00:01
.
.
.
23:59:59
Page 26 of 6
Problem #2
Write a nested loop to produce the following pattern if the
user input is 5
Page 27 of 6
Problem #3
Write a nested loop to produce the following pattern if the
user input is 5
Page 28 of 6
Summary
Page 29 of 13