Introduction to Computer Programming
Control Structures – Repetition
C++ Programming: From Problem Analysis to Program Design
1
• Basic loop structures
• while loops
• Interactive while loops
• for loops
• Loop programming techniques
• Nested loops
• do whileloops
• Common programming errors
Chapter Topics
2
• Suppose you want to add five numbers to find their
average. From what you have learned so far, you
could proceed as follows:
• Assume that all variables are properly declared
Why Is Repetition Needed?
3
Why Is Repetition Needed?
• Suppose you want to add and average 100, 1000, or
more numbers
– You would have to declare that many variables
– List them again in cin statements
• This takes an exorbitant amount of space and time
• Also, if you want to run this program again with
different values or with a different number of
values, you have to rewrite the program
4
• Suppose you want to add the following numbers:
5 3 7 9 4
• Consider the following statements, in which sum
and num are variables of type int:
1. sum = 0;
2. cin >> num;
3. sum = sum + num;
• Each time you need to add a new number, you
repeat statements 2 and 3
Why Is Repetition Needed?
5
• Repetition structure has four required elements:
– Repetition statement
– Condition to be evaluated
– Initial value for the condition
– Loop termination
• Repetition statements include:
– while
– for
– do while
Basic Loop Structures
6
f o r ( i = 0 ; i < 1 0 ; i + + )
c o u t < < i ;
• The condition can be tested
– At the beginning: Pretest or entrance‐controlled loop
(while, for)
– At the end: Posttest or exit‐controlled loop (do‐while)
• Something in the loop body must cause the
condition to change, to avoid an infinite loop, which
never terminates
Basic Loop Structures (continued)
7
• Pretest loop: Condition
is tested first; if false,
statements in the loop
body are never
executed
• while and for loops
are pretest loops
Pretest and Posttest Loops
A pretest loop
8
Pretest and Posttest Loops (continued)
• Posttest loop: Condition is
tested after the loop body
statements are executed;
loop body always executes
at least once
• do while is a posttest
loop
A posttest loop
9
• Fixed‐count loop: Loop is processed for a fixed
number of repetitions
• Variable‐condition loop: Number of repetitions
depends on the value of a variable
Fixed‐Count Versus Variable‐Condition
Loops
10
f o r ( i = 0 ; i < 1 0 ; i + + )
c o u t < < i ;
f o r ( i = 0 ; i < a ; i + + )
c o u t < < i ;
while Loops
• while statement is used to create a while loop
– Syntax:
while (expression)
statement;
• Statements following the expressions are executed
as long as the expression condition remains true
(evaluates to a non‐zero value)
11
while Loops (continued)
12
Loop repeated 10 times
Start value 1
End value 10
Increment 1
Last value of count is 11
while Loops (Examples)
13
Loop repeated 5 times
Start value 0
End value 20
Increment 5
Last value of i is 25
while Loops (Examples)
14
Loop repeated 0 times
Start value 20
End value N/A
Increment 5
Last value of i is 20
Counter‐Controlled while Loops
• Suppose that a set of statements needs to be executed N
times
• You can set up a counter (initialized to 0 before the while
statement) to track how many items have passed
15
Counter‐Controlled while Loops
16
Loop repeated limit times
Start value 0
End value limit ‐1
Increment 1
Last value of counter is limit
Counter‐Controlled while Loops
17
Counter‐Controlled while Loops
18
while Loops with Sentinels
• Sentinel: A data value used to signal either the start
or end of a data series
• Use a sentinel when you don’t know how many values
need to be entered (looping is controlled by the user)
19
while Loops with Sentinels
20
while Loops with Sentinels
21
while Loops with Sentinels
22
Flag‐Controlled while Loops
• A flag‐controlled while loop uses a bool variable to control
the loop.
• Suppose found is a bool variable. The flag‐controlled while
loop takes the following form:
23
• break statement
– Forces an immediate break, or exit, from
switch, while, for, and do-while
statements
– Violates pure structured programming, but is
useful for breaking out of loops when an unusual
condition is detected
break and continue Statements
24
• Example of a break statement:
break and continue Statements
(cont’d)
25
• continue statement
– Applies to while, do-while, and for statements;
causes the next iteration of the loop to begin
immediately
– Useful for skipping over data that should not be
processed in this iteration, while staying within the
loop
break and continue Statements
(cont’d)
26
• A continue statement where invalid grades are
ignored, and only valid grades are added to the total:
break and continue Statements
(cont’d)
27
• Null statement
– Semicolon with nothing preceding it
• ;
– Do‐nothing statement required for syntax purposes only
The Null Statement
28
for Loops
• for statement: A loop with a fixed count condition
that handles alteration of the condition
– Syntax:
for(initializing list; expression; altering list)
statement;
• Initializing list: Sets the starting value of a counter
• Expression: Contains the maximum or minimum value
the counter can have; determines when the loop is
finished
29
for Loops
30
Loop repeated 10 times
Start value 0
End value 9
Increment 1
Last value of i is 10
Note: Only this statement is executed with
the loop since there is no curled brackets.
• Altering list: Provides the increment value that is
added or subtracted from the counter in each
iteration of the loop
• If initializing list is missing, the counter initial value
must be provided prior to entering the for loop
• If altering list is missing, the counter must be altered
in the loop body
• Omitting the expression will result in an infinite loop
for Loops (continued)
31
for Loops (continued)
32
for loop
flowchart.
for Loops (cont’d)
33
for Loops (Examples)
34
for Loops (Examples)
35
for Loops (Examples)
36
• These techniques are suitable for pretest loops ( for
and while):
– Interactive input within a loop
• Includes a cin statement within a while or for loop
– Selection within a loop
• Using a for or while loop to cycle through a set of
values to select those values that meet some criteria
A Closer Look: Loop Programming
Techniques
37
A Closer Look: Loop Programming
Techniques (continued)
38
A Closer Look: Loop Programming
Techniques (continued)
39
A Closer Look: Loop Programming
Techniques (continued)
40
• Nested loop: A loop contained within another loop
– All statements of the inner loop must be completely
contained within the outer loop; no overlap allowed
– Different variables must be used to control each loop
– For each single iteration of the outer loop, the inner loop
runs through all of its iterations
Nested Loops
41
Nested Loops (continued)
For each i, j loops.
42
Nested Loops (continued)
43
• do while loop is a posttest loop
– Loop continues while the condition is true
– Condition is tested at the end of the loop
– Syntax:
do
statement;
while (expression);
• All statements are executed at least once in a
posttest loop
do while Loops
44
The do while
loop structure.
do while Loops
45
The do
statement’s
flow of control.
do while Loops
46
do while Loops (Examples)
47
Loop repeated 5 times
Start value 0
End value 25
Increment 5
Last value of counter is 25
• Useful in filtering user‐entered input and providing
data validation checks
• Can enhance with if-else statement
Validity Checks
48
• Using the assignment operator (=) instead of the equality
comparison operator (==) in the condition expression
• Placing a semicolon at the end of the for clause, which
produces a null loop body
• Using commas instead of semicolons to separate items in
the for statement
• Changing the value of the control variable
• Omitting the final semicolon in a do statement
Common Programming Errors
49
Summary
• Loop: A section of repeating code, whose
repetitions are controlled by testing a condition
• Three types of loops:
– while
– for
– do while
• Pretest loop: Condition is tested at beginning of
loop; loop body may not ever execute; ex., while,
for loops
50
Summary (continued)
• Posttest loop: Condition is tested at end of loop;
loop body executes at least once; ex., do while
• Fixed‐count loop: Number of repetitions is set in
the loop condition
• Variable‐condition loop: Number of repetitions is
controlled by the value of a variable
51

Repetition, Basic loop structures, Loop programming techniques

  • 1.
    Introduction to ComputerProgramming Control Structures – Repetition C++ Programming: From Problem Analysis to Program Design 1
  • 2.
    • Basic loopstructures • while loops • Interactive while loops • for loops • Loop programming techniques • Nested loops • do whileloops • Common programming errors Chapter Topics 2
  • 3.
    • Suppose youwant to add five numbers to find their average. From what you have learned so far, you could proceed as follows: • Assume that all variables are properly declared Why Is Repetition Needed? 3
  • 4.
    Why Is RepetitionNeeded? • Suppose you want to add and average 100, 1000, or more numbers – You would have to declare that many variables – List them again in cin statements • This takes an exorbitant amount of space and time • Also, if you want to run this program again with different values or with a different number of values, you have to rewrite the program 4
  • 5.
    • Suppose youwant to add the following numbers: 5 3 7 9 4 • Consider the following statements, in which sum and num are variables of type int: 1. sum = 0; 2. cin >> num; 3. sum = sum + num; • Each time you need to add a new number, you repeat statements 2 and 3 Why Is Repetition Needed? 5
  • 6.
    • Repetition structurehas four required elements: – Repetition statement – Condition to be evaluated – Initial value for the condition – Loop termination • Repetition statements include: – while – for – do while Basic Loop Structures 6 f o r ( i = 0 ; i < 1 0 ; i + + ) c o u t < < i ;
  • 7.
    • The conditioncan be tested – At the beginning: Pretest or entrance‐controlled loop (while, for) – At the end: Posttest or exit‐controlled loop (do‐while) • Something in the loop body must cause the condition to change, to avoid an infinite loop, which never terminates Basic Loop Structures (continued) 7
  • 8.
    • Pretest loop:Condition is tested first; if false, statements in the loop body are never executed • while and for loops are pretest loops Pretest and Posttest Loops A pretest loop 8
  • 9.
    Pretest and PosttestLoops (continued) • Posttest loop: Condition is tested after the loop body statements are executed; loop body always executes at least once • do while is a posttest loop A posttest loop 9
  • 10.
    • Fixed‐count loop:Loop is processed for a fixed number of repetitions • Variable‐condition loop: Number of repetitions depends on the value of a variable Fixed‐Count Versus Variable‐Condition Loops 10 f o r ( i = 0 ; i < 1 0 ; i + + ) c o u t < < i ; f o r ( i = 0 ; i < a ; i + + ) c o u t < < i ;
  • 11.
    while Loops • whilestatement is used to create a while loop – Syntax: while (expression) statement; • Statements following the expressions are executed as long as the expression condition remains true (evaluates to a non‐zero value) 11
  • 12.
    while Loops (continued) 12 Looprepeated 10 times Start value 1 End value 10 Increment 1 Last value of count is 11
  • 13.
    while Loops (Examples) 13 Looprepeated 5 times Start value 0 End value 20 Increment 5 Last value of i is 25
  • 14.
    while Loops (Examples) 14 Looprepeated 0 times Start value 20 End value N/A Increment 5 Last value of i is 20
  • 15.
    Counter‐Controlled while Loops •Suppose that a set of statements needs to be executed N times • You can set up a counter (initialized to 0 before the while statement) to track how many items have passed 15
  • 16.
    Counter‐Controlled while Loops 16 Looprepeated limit times Start value 0 End value limit ‐1 Increment 1 Last value of counter is limit
  • 17.
  • 18.
  • 19.
    while Loops withSentinels • Sentinel: A data value used to signal either the start or end of a data series • Use a sentinel when you don’t know how many values need to be entered (looping is controlled by the user) 19
  • 20.
    while Loops withSentinels 20
  • 21.
    while Loops withSentinels 21
  • 22.
    while Loops withSentinels 22
  • 23.
    Flag‐Controlled while Loops •A flag‐controlled while loop uses a bool variable to control the loop. • Suppose found is a bool variable. The flag‐controlled while loop takes the following form: 23
  • 24.
    • break statement –Forces an immediate break, or exit, from switch, while, for, and do-while statements – Violates pure structured programming, but is useful for breaking out of loops when an unusual condition is detected break and continue Statements 24
  • 25.
    • Example ofa break statement: break and continue Statements (cont’d) 25
  • 26.
    • continue statement –Applies to while, do-while, and for statements; causes the next iteration of the loop to begin immediately – Useful for skipping over data that should not be processed in this iteration, while staying within the loop break and continue Statements (cont’d) 26
  • 27.
    • A continuestatement where invalid grades are ignored, and only valid grades are added to the total: break and continue Statements (cont’d) 27
  • 28.
    • Null statement –Semicolon with nothing preceding it • ; – Do‐nothing statement required for syntax purposes only The Null Statement 28
  • 29.
    for Loops • forstatement: A loop with a fixed count condition that handles alteration of the condition – Syntax: for(initializing list; expression; altering list) statement; • Initializing list: Sets the starting value of a counter • Expression: Contains the maximum or minimum value the counter can have; determines when the loop is finished 29
  • 30.
    for Loops 30 Loop repeated10 times Start value 0 End value 9 Increment 1 Last value of i is 10 Note: Only this statement is executed with the loop since there is no curled brackets.
  • 31.
    • Altering list:Provides the increment value that is added or subtracted from the counter in each iteration of the loop • If initializing list is missing, the counter initial value must be provided prior to entering the for loop • If altering list is missing, the counter must be altered in the loop body • Omitting the expression will result in an infinite loop for Loops (continued) 31
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
    • These techniquesare suitable for pretest loops ( for and while): – Interactive input within a loop • Includes a cin statement within a while or for loop – Selection within a loop • Using a for or while loop to cycle through a set of values to select those values that meet some criteria A Closer Look: Loop Programming Techniques 37
  • 38.
    A Closer Look:Loop Programming Techniques (continued) 38
  • 39.
    A Closer Look:Loop Programming Techniques (continued) 39
  • 40.
    A Closer Look:Loop Programming Techniques (continued) 40
  • 41.
    • Nested loop:A loop contained within another loop – All statements of the inner loop must be completely contained within the outer loop; no overlap allowed – Different variables must be used to control each loop – For each single iteration of the outer loop, the inner loop runs through all of its iterations Nested Loops 41
  • 42.
    Nested Loops (continued) Foreach i, j loops. 42
  • 43.
  • 44.
    • do whileloop is a posttest loop – Loop continues while the condition is true – Condition is tested at the end of the loop – Syntax: do statement; while (expression); • All statements are executed at least once in a posttest loop do while Loops 44
  • 45.
    The do while loopstructure. do while Loops 45
  • 46.
    The do statement’s flow ofcontrol. do while Loops 46
  • 47.
    do while Loops(Examples) 47 Loop repeated 5 times Start value 0 End value 25 Increment 5 Last value of counter is 25
  • 48.
    • Useful infiltering user‐entered input and providing data validation checks • Can enhance with if-else statement Validity Checks 48
  • 49.
    • Using theassignment operator (=) instead of the equality comparison operator (==) in the condition expression • Placing a semicolon at the end of the for clause, which produces a null loop body • Using commas instead of semicolons to separate items in the for statement • Changing the value of the control variable • Omitting the final semicolon in a do statement Common Programming Errors 49
  • 50.
    Summary • Loop: Asection of repeating code, whose repetitions are controlled by testing a condition • Three types of loops: – while – for – do while • Pretest loop: Condition is tested at beginning of loop; loop body may not ever execute; ex., while, for loops 50
  • 51.
    Summary (continued) • Posttestloop: Condition is tested at end of loop; loop body executes at least once; ex., do while • Fixed‐count loop: Number of repetitions is set in the loop condition • Variable‐condition loop: Number of repetitions is controlled by the value of a variable 51