DEV Community

Cover image for Nested Loops
Paul Ngugi
Paul Ngugi

Posted on

Nested Loops

A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. The program uses nested for loops to display a multiplication table.

Image description

The program displays a title (line 7) on the first line in the output. The first for loop (lines 11-12) displays the numbers 1 through 9 on the second line. A dashed (-) line is displayed on the third line (line 14). The next loop (lines 17-24) is a nested for loop with the control variable i in the outer loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner loop, with j being 1, 2, 3, . . ., 9.

Be aware that a nested loop may take a long time to run. Consider the following loop nested in three levels:

for (int i = 0; i < 10000; i++)
 for (int j = 0; j < 10000; j++)
 for (int k = 0; k < 10000; k++)
 Perform an action
Enter fullscreen mode Exit fullscreen mode

The action is performed one trillion times. If it takes 1 microsecond to perform the action, the total time to run the loop would be more than 277 hours. Note that 1 microsecond is one millionth (10– 6) of a second.

Top comments (0)