Looping - PowerPoint PPT Presentation

1 / 74
About This Presentation
Title:

Looping

Description:

Count-controlled loops. They contain: An initialization of the loop control ... If the stream has entered a fail state, it has a false, otherwise it has a true ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 75
Provided by: bridges
Category:

less

Transcript and Presenter's Notes

Title: Looping


1
Looping
  • Reading Chapter 5

2
What 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

3
Types of Loop Testing
4
Pretest 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 . . .
5
Loops 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

6
Count-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

7
Count-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
8
Count-controlled Loop
count
  • int count
  • count 4
  • while (count gt 0)
  • cout ltlt count ltlt endl
  • count--
  • cout ltlt "Done" ltlt endl

Output
9
Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
4
Output
10
Count-controlled Loop
count
int count count 4 while (count gt 0) cout
ltlt count ltlt endl count-- cout ltlt "Done"
ltlt endl
4
Output
11
Count-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
12
Count-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
13
Count-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
14
Count-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
15
Count-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
16
Count-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
17
Count-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
18
Count-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
19
Count-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
20
Count-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
21
Count-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
22
Count-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
23
Count-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
24
Event-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

25
Examples of Kinds of Loops
26
A 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

27
Example
  • 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

28
End-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

29
Using 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

30
Combining 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

31
eof 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

32
Assignment
  • 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

33
Flag-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

34
Example
  • 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

35
Posttest 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)
36
Example
// 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
37
Sentinel-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
38
while vs. do while
39
Accumulating
  • Loops often used to
  • Count data values
  • Sum data values
  • Keep track of previous and current values
  • This requires accumulating and counting

40
Accumulating (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

41
Accumulating (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
42
Example
// 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
43
Assignment
  • Write a C program to calculate the factorial of
    10.

44
The for loop
  • A specially designed count-controlled loop

for (initialization test updatecounter)
statement
for (initialization test updatecounter)
statement1 statement2 . . .
45
The 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

46
Example
int count for (count 1 count lt 3
count) cout ltlt count ltlt endl cout ltlt
"Count " ltlt count ltlt endl
47
Example (Cont ..)
count
  • int count
  • for (count 1 count lt 3 count)
  • cout ltlt count ltlt endl
  • cout ltlt "Count " ltlt count ltlt endl

Output
48
Example (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
49
Example (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
50
Example (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
51
Example (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
52
Example (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
53
Example (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
54
Example (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
55
Example (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
56
Example (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
57
Example (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
58
Example (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.
59
Example (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
60
Assignment
  • Write a program to ask the user to enter 5
    integers and then find the maximum value.

61
Programming 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 ""

62
Programming 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

63
Programming 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

64
Programming 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
65
Programming 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
66
Nested 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

67
Example 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
68
Assignment
Write a program to display the following output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
69
Validation 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

70
Example
  • 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

71
Example (Cont ..)
  • Output
  • Enter the test score -18
  • Invalid input, enter again 110
  • Invalid input, enter again 89
  • The test score is 89

72
The 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.

73
The 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.

74
Loop 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
Write a Comment
User Comments (0)
About PowerShow.com