Chapter 7: Loops
Looping constructs:
- for (count-controlled)
- while (condition-controlled)
- do/while
Sections 7.1-7.3
A bit of a hodge-podge of examples.
Counting and summing variables:
- Loop counters in "for"
- The accumulators total and totalvalid in program 5
- sum1.cpp.
- count1.cpp.
while:
while(condition)
{
statements
}
Example of a loop that is not count-controlled (fixed-step):
eat dinner
while (there is a dirty dish)
wash one dish
do homework
Ch7 starts with fixed step loops where you count how many times it it executed.
Printing hello 5x:
Counting by 3:
These are fixed-step. Exit condition is solely determined by the counter final value.
Using chars as loop counters: 1,
2.
Pitfall:
generating an infinite loop when you don't mean to.
What is happening here:
while (count <=10)
cout << "hello";
count++;
while (count <=10); //a silent infinite loop
{
cout << "hello";
count++;
}
inf1.cpp
inf2.cpp
Is an infinite loop ever a good idea?
Yes, the keyboard operates this way.
while (true)
{
read next keystroke
process it
}
Section 7.4
For loops to input groups of data.
(some review)
- sum1.cpp finds the sum of 10 numbers
- How do we add just the positive numbers? sum2.cpp
- How do we find the average? add avg to it: avg1.cpp
- The average of the positive numbers: avg2.cpp.
- Suppose I want sum2 to run for a user-specified #: sum3.cpp
Section 7.5
More on designing for loops:
finding a maximum: 1,
2.
Section 7.6 While versus Do
do{
statements
}
while (condition)
do.cpp
7.7 User-controlled data with while and do..while loops
findsum.cpp: uses a sentinal
receipts.cpp (needed for assignment 7, simpler logic but clunkier
since you have to type y each time).
7.8 Debugging Strategies
- insert extra cout
- debugger (built-in, not very friendly)
- hand tracing