PROG
Print out a table of i*j where i goes from 1 to 3 and j goes from 1 to 3.
PED
To learn how to nest do loops.
DO LOOP INVARIANT
Outer do loop
We have computed i*j for all integers from 1 to i-1
Inner do loop
We have computed i*j for the current value of i and for all integers, j,
from 1 to j-1
Click here to view Unit 4.9 Pascal program.
We now learn how to nest while loops--that is, to have one while loop into another.Let's make believe your employer, Chicago Real Estate Company, has two lots and some money to invest in building some apartment complexes. There would be one complex on each lot, for a total of two buildings. Each apartment complex will contain from 1 to 10 floors. Your employer would like to know what his profit, cash flow etc, would be for all possible combinations. Using what you have learned from a Real Estate Investment course, tax law, etc. you figure out formulae for these financial numbers which are a function of i and j. i represents the number of floors in a possible building in complex 1. j represents the number of floors in a possible building in complex 2.
What you want to do is for each possible value of i from 1 to 10, compute all the numbers for that value of i and for each of the values of j. That would mean that 100 sets of numbers would be printed out.
This unit teaches you how to do this. In order to keep the program simple, I will assume that we will print out for each value of i and j, i, j and i*j as the single formula. Also, we will go from 1 to 3 for i and from 1 to 3 for j. (This will make it much easier to go through by hand on the board in class!).
We can write this using the pseudocode
for each value of i from 1 to 3
print out i*j for j from 1 to 3
The latter is a simple while loop giving us the code. It is very similar to the code of
Unit 4.3 to do something a given number of times.
i:=1;
while(i<=3) do begin
print out i*j for j from 1 to 3
i:=i+1;
end;
A good way to think about this is as some kind of odometer. j is like the unit's wheel. i is like the ten's wheel. It goes up three. When it hits three, it goes back to 1, but the other wheel is incremented.
Replacing "print out i*j for j from 1 to 3" by appropriate code gives us the program in front. By the way, I had to put ' ' between the values of i, j and i*j so the data would be readable. When several numbers are written on a line, Turbo Pascal doesn't automatically assume you want a space between them. Other Pascal's will put some kind of space there.