Keywords: pame

Subsections

- Exercises

# Nested loops

When dealing with two-, and higher-dimensional multiples, it is often necessary to run a subsidiary loop. For example, suppose we wanted to print the square of each element in the multiple declared as

       [,]INT primes = (( 2, 3, 5, 7),
                        (11,13,17,19),
                        (23,29,31,37),
                        (41,43,47,53))

with each row on one line. Here is a piece of program which will do it:

       FOR i FROM 1 LWB primes TO 1 UPB primes
       DO
          []INT pri=primes[i,];

          FOR j FROM LWB pri TO UPB pri
          DO
             INT prij = pri[j];
             print(prij * prij)
          OD;
          print(newline)
       OD

Notice the optimisations. The first defines the ith "row", and the second defines the jth element in that "row". The point is that any piece of program can appear inside the loop clause. Loop clauses can be nested to any depth. Because the loop clause is an enclosed clause, it must contain at least one phrase, and the last phrase must be a unit (see chapter 10 for a thorough discussion of units).

## Exercises

3.13
  Using a nested loop, write a short program to display the first 25 letters of the alphabet on your screen in five rows of five letters. Separate each letter with a comma. Ans
3.14
  Write a program to print the value of a 3-dimensional multiple of real numbers which you have declared in your program. Ans