4.4 Nested Loops

There are times in programs where you will need to put a loop inside a loop. This is called nesting loops. Here is an example of nested for loops:

% outer loop starts
for row : 1 .. 5
   % inner loop starts
   for col : 1 .. row
      put col ..
   end for % inner loop ends
   put ""
end for % outer loop ends

The outer for loop using row will be executed 5 times. The variable row will take on the values 1 through 5. The inner loop using col will thus be executed 5 times. It will loop once the first time, twice the second, three times the third and so on. Here is the output:

1
12
123
1234
12345

You can also nest loop statements. Suppose you wanted to find the average mark for several classes. Here is a program that would do that:

var response : string
var sum, count, mark : int
var average : real

put "Do you want to calculate an average?"
get response

%********************************** outer loop
loop
   exit when response not= 'y' and response not='Y'
   sum := 0
   count := 0
   
   % ************  inner loop
   loop
      put "Enter mark # ", count + 1
      get mark
      exit when mark < 0
      sum := sum + mark
      count := count + 1
   end loop 
   % ************  End of inner loop
   
   if count = 0 then
      put "No marks entered, can't compute average."
   else
      average := sum / count
      put "The average mark is ", average
   end if
   
   put "Do you want to calculate another average?"
   get response
end loop
%********************************** End of outer loop 

Here is an example of the output:

Do you want to calculate an average?
Y
Enter mark # 1
80
Enter mark # 2
90
Enter mark # 3
85
Enter mark # 4
-1
The average mark is 85
Do you want to calculate another average?
y
Enter mark # 1
99
Enter mark # 2
97
Enter mark # 3
67
Enter mark # 4
77
Enter mark # 5
97
Enter mark # 6
-3
The average mark is 87.4
Do you want to calculate another average?
n

Exercise 4.4

  1. What does this program print?
    const numberOfRows := 7
    
    for i : 0 .. numberOfRows - 1
       put " ":numberOfRows - i, '*' ..
       for j : 1 .. i
          put "**" ..
       end for
       put ""
    end for 
  2. Write a program that will print a pattern like the one shown below, where the dots indicate other asterisks in the pattern. The maximum width of the pattern should be read by the program.
    *
    **
    .
    .
    ***...*
    .
    .
    **
    *
  3. Let N be a positive integer consisting of the digits dn...d 1d0.
    1. Write a program that reads a value of N and then prints its digits in a column, starting with d0. For example, if N has the value 3467, the program should print

      7
      6
      4
      3

    2. Rewrite the program so that it prints the digits of N in reverse order, starting with dn and working down to d0.
  4. Write a program using nested loops that prints the following pattern.

    54321
     4321
      321
       21
        1