|
|
|
|
|
|
|
sible for an outer loop to do no processing other than to execute the inner loop repeatedly. On the other hand, the inner loop might be just a small part of the processing done by the outer loop; there could be many statements preceding or following the inner loop. |
|
|
|
|
|
|
|
|
Let's look at another example. For nested count-controlled loops, the pattern looks like this (where outCount is the counter for the outer loop, inCount is the counter for the inner loop, and limit1 and limit2 are the number of times each loop should be executed): |
|
|
|
|
|
|
|
|
outCount = 1; // Initialize outer loop counter
while (outCount <= limit1)
{
.
.
.
inCount = 1; // Initialize inner loop counter
while (inCount <= limit2)
{
.
.
.
inCount++; // Increment inner loop counter
}
.
.
.
outCount++; // Increment outer loop counter
} |
|
|
|
|
|
|
|
|
Here, both the inner and outer loops are count-controlled loops, but the pattern can be used with any combination of loops. The following program fragment shows a count-controlled loop nested within an EOF-controlled loop. The outer loop inputs an integer value telling how many asterisks to print out across a row of the screen. (We use the numbers to the right of the code to trace the execution of the program below.) |
|
|
|
|
|
|
|
|
cin >> starCount; 1
while (cin) 2
{
loopCount = 1; 3
while (loopCount <= starCount) 4
{
cout << '*'; 5
loopCount++; 6
}
cout << endl; 7
cin >> starCount; 8
}
cout << "Goodbye" << endl; 9 |
|
|
|
|
|