Programming made easy – nested loops
We’re not quite done with loops yet. There are still a few things to learn, although some can be left for later. There are certain situations where it is appropriate to use a loop inside another loop. Such a loop is called a nested loop. A nested loop is executed, essentially, from the inside out. Each loop is like a layer and has its own loop control, its own condition and its own loop body. Below is a schematic of three nested loops.
There are many different kinds of nested loops, and they are largely dependent on the underlying algorithm. Below are some examples of the types of nested loops that are possible.
We will consider how a nested loop can be used to create a times table. It basically works by iterating the inner loop 12 times for every iteration of the outer loop. So, 12 × 12 = 144 iterations. The outer loop is highlighted in blue, and the inner loop in red. Here is a sample output:
1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 5 10 15 20 25 30 35 40 45 50 55 60 6 12 18 24 30 36 42 48 54 60 66 72 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132 12 24 36 48 60 72 84 96 108 120 132 144
Ada
with ada.Text_IO; use Ada.Text_IO; with ada.Integer_Text_IO; use ada.Integer_Text_IO; procedure nested is begin for x in 1..12 loop for y in 1..12 loop put(x*y, width=>4); end loop; new_line; end loop; end nested;
Fortran
program nested integer :: x, y do x = 1, 12 do y = 1, 12 write(*,10,advance='no') xy 10 format(I4) end do write(*,*) end do end program nested
C
#include <stdio.h> int main(void){ int x, y; for (x=1; x<=12; x=x+1) { for (y=1; y<=12; y=y+1) printf("%4d", x*y); printf("\n"); } return 0; }
Julia
for x = 1:12 for y = 1:12 @printf("%4d", x*y) end println() end println(h)
spqr