A logical structure used in computer programming where two or more repeating statements are placed in a "nested" form (i.e., one loop is situated within the body of another). The inner loop is repeated in full on every pass through the outer loop.
A nested loop is a loop control structure which contains a (inner) loop within it, aka a loop within a loop.
Nested loops are often used to loop through all the elements of a multidimensional array or a matrix.
Here is an example code demonstrating a nested loop: It enumerates all the pairs (x, y)
, where x
ranges from 0 to 3, and y
ranges from 0 to 2, as well as print out when did the outer and inner loop finish.
int x = 0;
int y = 0;
while (x <= 3) {
while (y <= 2) {
printf("(%d, %d)\n", x, y);
y++;
}
printf("Inner Loop finished\n");
x++;
y = 0;
}
printf("Outer Loop finished\n");
This double loop would run as follows:
(0, 0)
(0, 1)
(0, 2)
Inner Loop finished
(1, 0)
(1, 1)
(1, 2)
Inner Loop finished
(2, 0)
(2, 1)
(2, 2)
Inner Loop finished
(3, 0)
(3, 1)
(3, 2)
Inner Loop finished
Outer Loop finished