What is nested loop?

What is nested loop?

  • C programming allows to use one loop inside another loop. This is called nested loop.

There are three basic types of loop:

  1. The for loop which executes the repeated instructions a fixed number of times, or iterations.
  2. The while loop which executes its instructions while the test that controls the loop is true. The while loop tests its condition before each iteration of the loop.
  3. The do while loop is similar to the while loop but it tests its condition after each iteration of the loop.

Nesting is simply a term given to the use of one or more loops within another, where for each iteration of the outer loop, the inner loop iterates numerous times. An analogy here is a 12 hour clock: the hour hand (outer loop) moves only once an hour from 1 o’clock to 2 o’clock, 2 o’clock to 3 and so on, but for each hour, the minute hand (inner loop) moves sixty times.

The following example demonstrates a pair of nested for loops using the Java language:

  1. public class NestedLoopDemo {
  2.                 public static void main(String[] args) {
  3.                                 for (int row = 1; row <= 3; row++) { // Outer loop.
  4.                                                 for (int col = 1; col <= 3; col++) { // Inner loop.
  5.                                                                 System.out.println(row + ” ” + col); // Print values of row col.
  6.                                                 }
  7.                                 }
  8.                 }
  9. }

In this example, the two loops print:

  1. 1 1
  2. 1 2
  3. 1 3
  4. 2 1
  5. 2 2
  6. 2 3
  7. 3 1
  8. 3 2
  9. 3 3

In the outer loop, we use a variable (an item of data denoted here by int, i.e. whole numbers) called row which runs from 1 to 3 (left hand side). But for each iteration of this loop, the inner loop also runs three times from 1 to 3 according to the variable col (right hand side). So when the row variable of the outer loop is set to 1, the inner loop runs three times producing:

  1. 1 1
  2. 1 2
  3. 1 3

In its first iteration, 1 is produced by the outer loop using variable row (left hand side), and the right hand side’s numbers 1, 2 and 3 are produced by the inner loop’s variable col. Only when the inner loop has completed three iterations for the outer loop’s one iteration, will the left hand side’s number change to 2. And then the inner loop will run again through its three iterations, and so on.

Nesting frequently sees the same loop type used but this is not always the case: it is quite possible to have an outer while loop and an inner for loop or vice versa. Nesting can also require multiple loops, not just two.

 

Please follow and like us:

Leave a Reply

Your email address will not be published.