Title: Iterative Structures: for Loops
1Iterative Structures for Loops
- Lecture 13 Wed, Sep 24, 2003
2Loops Controlled by a Counter
- If we know in advance the number of times a loop
should be executed, then we can count the
iterations and quit at the proper time. - Establish a counter and do the following.
- Initialize the counter to 0.
- Test the counter on each iteration.
- Increment the counter.
3Loops Controlled by a Counter
- If the counter controls the loop, then the
testing does not involve the input. - Therefore, the pattern prompt-read-test-action is
no longer in effect. - Indeed, there may not be any input.
4Loops Controlled by a Counter
int limit cin gtgt limit int counter 0 while
(counter lt limit) Prompt user for input
cin gtgt number Action counter
5Example of a Counter
6Combining the Methods
- A loop may be controlled by a combination of
methods. - For example, we may use a sentinel value of 1,
but also test for EOF. - This loop would be controlled by both a sentinel
value and end-of-file.
7Combining the Methods
- The sequence should be
- Prompt user for input
- Read input
- Test input and test for EOF
- Action
- Prompt user for input
- Read input
- Test input and test for EOF
- Action
- And so on
8Combining the Methods
const int SENTINEL -1 Prompt user for
input cin gtgt number while (!cin.eof() number
! SENTINEL) Action Prompt user for
input cin gtgt number
9Example of a Sentinel Value and EOF
10Combining the Methods
- As another example, we may use a sentinel value
of 1, but also not read more than 100 numbers. - This loop would be controlled by both a sentinel
value and a counter. - This is trickier, as we discover when we write
the sequence of steps.
11Combining the Methods
- The sequence should be
- Initialize counter
- Test counter
- Prompt user for input
- Read input
- Test input
- Action
- Increment counter
- Test counter
- And so on
12Combining the Methods
- This loop requires two tests and they must occur
at different points. - This is one of the rare cases where it is
justifiable to break out of a loop prematurely. - Place one test in the while statement.
- Place the other test in the body of the loop
together with a break statement.
13Combining the Methods
const int LIMIT 100 const int SENTINEL
-1 int counter 0 while (counter lt limit)
Prompt user for input cin gtgt number if
(number SENTINEL) break Action
counter
14Example of a Sentinel Value and a Counter
15The for Statement
- Loops controlled by counters are very common.
- To facilitate their use, C provides a for
statement. - The for statement controls the loop by
- Initializing the counter
- Testing the counter
- Incrementing the counter
16The for Statement
for (Init counter Test counter Incr counter)
Action
for (int i 0 i lt 10 i) cout ltlt "Enter
a number " cin gtgt number sum
number
17Examples of a for Loop
- ForSum.cpp
- CountLetters.cpp