The inner loop begins by initializing j to 1. Since 1 is not greater than 12, the first pass through the inner loop begins. The first statement of this loop computes the product of i and j. Since they are both 1, their product is 1. Next, the following four items are printed on a single line: the current value of i, the string “ times ”, the current value of j, and the string “ equals ”. These are followed by the current value of product and a new line character. Thus the string “1 times 1 equals 1” is generated. The first pass of the inner loop ends with j being incremented from 1 to 2 and control returning to the top of that loop.
Each pass through the inner loop proceeds in a similar fashion, with i remaining constant and j being bumped up by one each time. So, during the second pass “1 times 2 equals 2” is printed, during the third “1 times 3 equals 3” is display, and so forth. Eventually, j reaches 12 and “1 times 12 equals 12” is output. j is then incremented to 13 and control returns to the top of the inner loop. Since 13 is greater than 12 the inner loop completes.
Execution of the first pass through the outer loop can now resume. Since the inner loop was the last “statement” of the outer loop, the loop variable i is incremented by 1, to 2, and control returns to the top of the outer loop.
The current value of i, 2, is not greater than 12, so the second pass through the outer loop begins. The first statement generates a blank line, as it did during the first pass through the loop. Next, the inner loop is encountered and its execution starts afresh. j is initialized to 1. Since that value is less than 12 the statements of the loop are executed and the string “2 times 1 equals 2” is printed. Subsequent passes through the inner loop produce “2 times 2 equals 4”, “2 times 3 equals 6”, etc. Eventually, of course, the inner loop will again complete and the third pass of the outer loop can begin.
This process repeats itself until all 144 entries in the multiplication table, from 1 ∙ 1 to 12 ∙ 12, are computed and printed.
Timing: s |
Figure 8.24: Beer – the iterative version
It continues in this manner, with one less bottle in each verse, until it finally runs out of beer. Actually, instead of beginning the song at 99 bottles, the program of Figure 8.24 asks the user to enter the number of bottles.
An interesting feature of the program is that it decrements count in the middle of the loop, rather than at the end. You should trace through the program with a few bottles to convince yourself that it does work properly. One thing you will probably notice as you do so is that when the program gets down to one beer it reports that as “1 bottles of beer on the wall.” While this lack of grammatical correctness might not seem like such a big deal, especially after 98 beers, I’ll ask you to correct it in the exercises.