Title: Looping
1Looping
2What is a Loop?
- A loop is a repetition control structure
- It causes a single statement or a group of
statements to be executed repeatedly - It uses a condition to control iteration
- Loop continues as long as condition is TRUE
3Types of Loop Testing
4Pretest Loops in C
- One pretest loop in C is the while loop
- A condition is used to control the loop
- The condition is put between parentheses
while (condition) statement
while (condition) statement1
statement2 . . .
5Loops can be ...
- Count controlled
- repeat a specified number of times
- Event-controlled
- some condition within the loop body changes and
this causes the repeating to stop
6Count-controlled loops
- They contain
- An initialization of the loop control variable
- A condition to test for continuing the loop
- An update of the loop control variable to be
executed with each iteration of the body
7Count-controlled Loop
int count count 4 // initialize loop
variable while (count gt 0) // test condition
cout ltlt count ltlt endl // repeated action
count-- // update loop
variable cout ltlt "Done" ltlt endl
8Count-controlled Loop
count
- int count
- count 4
- while (count gt 0)
-
- cout ltlt count ltlt endl
- count--
-
- cout ltlt "Done" ltlt endl
Output
9Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
4
Output
10Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
4
Output
11Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
4
Output
4
12Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
3
Output
4
13Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
3
Output
4
14Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
3
Output
4
3
15Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
2
Output
4 3
16Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
2
Output
4 3
17Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
2
Output
4 3
2
18Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
1
Output
4 3 2
19Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
1
Output
4 3 2
20Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
1
Output
4 3 2
1
21Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
0
Output
4 3 2 1
22Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
0
Output
4 3 2 1
23Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
0
Output
4 3 2 1
Done
24Event-controlled Loops
- Sentinel controlled
- keep processing data until a special value which
is not a possible data value is entered to
indicate that processing should stop - End-of-file controlled
- keep processing data as long as there is more
data in the file - Flag controlled
- keep processing data until the value of a flag
changes in the loop body
25Examples of Kinds of Loops
26A Sentinel-controlled Loop
- Sentinel value A special value of input that
causes the program to stop a loop - Must be a value that would not occur in the
normal course of operation - Requires a priming read if done with a while
loop - priming read means you read one set of data
before the while
27Example
- int bloodPressure, total 0
- cout ltlt "Enter a blood pressure (-1 to stop ) "
- cin gtgt bloodPressure
- while (bloodPressure ! -1) // while not sentinel
-
- total total bloodPressure
- cout ltlt "Enter a blood pressure (-1 to stop)
" - cin gtgt bloodPressure
-
- cout ltlt total ltlt endl
28End-of-File Controlled Loop
- Depends on fact that a file goes into fail state
when you try to read a data value beyond the end
of the file - Several ways to accomplish
29Using the ifstream variable
- Uses a priming read
- The variable alone is the loop control variable
- If the stream has entered a fail state, it has a
false, otherwise it has a true - ifstream inFile(data.txt)
- int x
- inFile gtgt x
- while(inFile)
- //Statements
- inFile gtgt x
30Combining the steps
- The priming read can be done as part of the
condition - The logic is still the same as the previous slide
- ifstream inFile(data.txt)
- int x
- while(inFile gtgt x)
-
- //statements
31eof Function
- eof function returns a true if the program has
read past the end of the file otherwise it
returns a false - Requires priming read
- ifstream inFile(data.txt)
- int x
- inFile gtgt x
- while(!inFile.eof())
-
- //Statements
- inFile gtgt x
32Assignment
- With a partner write two loops that would read
from the same file, money.dat, and print the
contents to the screen. - The program should loop until the end of the file
is reached. - Each of the two loops should use a different
method
33Flag-controlled Loops
- Use a bool type flag variable and initialize it
(to true or false) - Use meaningful name for the flag
- A condition in the loop body changes the value of
the flag - Test for the flag in the loop test condition
34Example
- int bloodPressure, countGoodReadings 0
- bool isSafe true // initialize Boolean flag
- while (isSafe)
-
- cin gtgt bloodPressure
- if (bloodPressure gt 200)
- isSafe false // change flag value
- else
- countGoodReadings
-
- cout ltlt countGoodReadings ltlt endl
35Posttest Loops in C
- Posttest done with the do while statement.
- Also uses a condition placed in parentheses.
do statement while (condition)
do statement1 statement2 . . .
while (condition)
36Example
// display the numbers from 4 to 0 // using the
posttest do while loop int count count 4
// initialize loop variable do
cout ltlt count ltlt endl // repeated action
count-- // update loop variable
while (count gt 0) // test condition cout
ltlt "Done" ltlt endl
37Sentinel-controlled loops with do while
- Does not require a priming read
int bloodPressure 0, total 0 do total
total bloodPressure cout ltlt "Enter a blood
pressure (-1 to stop) " cin gtgt
bloodPressure while (bloodPressure ! -1) //
while not sentinel cout ltlt total ltlt endl
38while vs. do while
39Accumulating
- Loops often used to
- Count data values
- Sum data values
- Keep track of previous and current values
- This requires accumulating and counting
40Accumulating (Cont ..)
- Accumulating is keeping a running result
- Take the value of a variable, modify the value,
and store it back in the original variable - total total new
- Any arithmetic operator (? ? / ) can be part
of an accumulation - total total new
- Counting is a simple form of accumulation
- count count 1
- Make sure you INITIALIZE accumulation or counting
variables
41Accumulating (Cont ..)
- Accumulation operators
- Shorthand for performing accumulation
- Same precedence associativity as assignment
Example Equivalent statement total
new total total new total - new total
total - new total new total total
new total / new total total / new total
new total total new
42Example
// calculate the sum of the integers from 1 to
10 // Initialize the counting and accumulating
variables int number 1, sum 0 while (
number lt 10) sum number // accumulating
the sum // sum sum number
number 1 // counting, number number
1 cout ltlt "The sum is " ltlt sum ltlt endl
43Assignment
- Write a C program to calculate the factorial of
10.
44The for loop
- A specially designed count-controlled loop
for (initialization test updatecounter)
statement
for (initialization test updatecounter)
statement1 statement2 . . .
45The for loop
- Actions of the for spread out around the loop
- initialization occurs only ONCE at the start
- testing is the first repeated action of the loop
(it gets done before the body each iteration) - updatecounter occurs at the end of the loop body
46Example
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
47Example (Cont ..)
count
- int count
- for (count 1 count lt 3 count)
-
- cout ltlt count ltlt endl
-
- cout ltlt "Count " ltlt count ltlt endl
Output
48Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
1
Output
49Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
1
Output
50Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
1
Output
1
51Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
2
Output
1
52Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
2
Output
1
53Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
2
Output
1 2
54Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
3
Output
1 2
55Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
3
Output
1 2
56Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
3
Output
1 2 3
57Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
4
Output
1 2 3
58Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
4
Output
1 2 3
When the loop control condition is evaluated and
has value false, the loop is said to be
satisfied and control passes to the statement
following the for structure.
59Example (Cont ..)
count
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
4
Output
1 2 3 Count 4
60Assignment
- Write a program to ask the user to enter 5
integers and then find the maximum value.
61Programming Error I
- What output do you expect from this loop?
- int count
- for (count 0 count lt 10 count)
- cout ltlt ""
- What about this one?
- int count
- for (count 0 count lt 10 count)
- cout ltlt ""
62Programming Error I (Cont ..)
- The second loop in the previous slide does not
produce any output. Why? - The right after the ( ) means that the body
statement is a null statement - In general, the Body of the for loop is whatever
statement immediately follows the ( ) - That statement can be a single statement, a
block, or a null statement - Actually, the second code segment in the previous
slide outputs one after the loop completes its
counting to 10
63Programming Error II
- C will accept any simple data type as a
counter, but floating-point counters can lead to
unexpected results - Floating-point values are stored in E- notation
and approximated to decimal values - So the value 1.0 might be approximated to
1.000000000001 or 0.999999999999
64Programming Error II (Cont ..)
float count cout ltlt "Values from 0 to 1 in steps
of 0.1\n" ltlt endl cout ltlt fixed ltlt
setprecision(2) for (count 0 count lt 1
count 0.1) cout ltlt count ltlt " " cout ltlt
endl ltlt "Final count " ltlt count ltlt endl
Possible Output Values from 0 to 1 in steps of
0.1 0.00 0.10 0.20 0.30 0.40 0.50 0.60
0.70 0.80 0.90 Final count 1.00
65Programming Error II (Cont ..)
int count cout ltlt "Values from 0 to 1 in steps
of 0.1\n" ltlt endl cout ltlt fixed ltlt
setprecision(2) for (count 0 count lt 10
count) cout ltlt count/10.0 ltlt " " cout ltlt
endl ltlt "Final count " ltlt count/10.0 ltlt endl
Output Values from 0 to 1 in steps of 0.1 0.00
0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80
0.90 1.00 Final count 1.10
66Nested Loops
- A loop within another is a nested loop
- Nest as deep as you want, but
- An inner loop must be entirely contained within
an outer one - If the loops are counter controlled, each loop
must have a different loop counter variable - Nested loops used often for rows and columns
- Outer loop controls the rows
- Inner loop controls the columns
67Example of Nested Loops
int column, row for (row 1 row lt 4
row) for (column 1 column lt 5
column) cout ltlt setw(2) ltlt row column
ltlt " " cout ltlt endl
Output
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4
8 12 16 20
68Assignment
Write a program to display the following output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
69Validation Loops
- Sometimes you may need to check for validity of
input data - The user can enter negative value where it is
supposed to be positive (year) - The user can enter a value that is outside the
range of possible values (entering 110 for a test
score) - This can be done with validation loops
- Continue prompting the user for valid value as
long as invalid value is entered
70Example
- int score
- cout ltlt "Enter the test score "
- cin gtgt score
- // test score should be between 0 and 100
- while ( score gt 100 score lt 0)
-
- cout ltlt "Invalid input, enter again "
- cin gtgt score
-
- cout ltlt endl ltlt "The test score is " ltlt score ltlt
endl
71Example (Cont ..)
- Output
- Enter the test score -18
- Invalid input, enter again 110
- Invalid input, enter again 89
- The test score is 89
72The break statement
- The break statement can be used with switch or
any of the 3 looping structures. - It causes an immediate exit from the switch,
while, do while, or for structure in which it
appears. - If the break is inside nested structures, control
exits only the innermost structure containing it.
73The continue statement
- The continue statement is valid only within
loops. - It terminates the current loop iteration, but not
the entire loop. - In a for or while loop, continue causes the rest
of the body statement to be skipped - in a for
statement, the update is done. - In a do while loop, the exit condition is tested,
and if true, the next loop iteration starts.
74Loop Testing and Debugging
- Beware of infinite loops - program doesnt stop
- Check loop termination condition, and watch for
off-by-1 problem - Trace execution of loop by hand with code
walk-through - Use debug output statements