Search code examples
cloopsnested-loops

Can someone help me fully understand this nested loop?


So I have generally understood looping pretty well, although my main concern lies with nested loops. I have provided an example from by book here:

#include <stdio.h>

int
main(void)
{
    int i, j;                           /* loop control variables */

    printf("           i    j\n");      /* prints column labels */

    for (i = 1;  i < 4;  ++i) {         /* heading of outer for loop */
        printf("Outer %6d\n", i);
        for (j = 0;  j < i;  ++j) {     /* heading of inner loop */
            printf("  Inner %9d\n", j);
        }   /* end of inner loop */
    }   /* end of outer loop */

    return (0);
}

The expected output is given as:

           i    j
Outer      1
  Inner         0
Outer      2
  Inner         0
  Inner         1
Outer      3
  Inner         0
  Inner         1
  Inner         2

My book does not do a great job at explaining how these loops work, and rather just shows us the code and the output.

Why does it start by only printing i, then j, then printing the incremented i, but then start j over again?

I want to be able to understand this concept so I can fully utilize it when I need it, and I am having trouble finding answers online.

Thanks.


Solution

  • The entire inner loop runs once for every single iteration of the outer loop. That inner loop includes the initialisation of j to 0, and the printing and incrementing of it up to, but not including, the current i (from the outer loop).

    So, for the first outer iteration where i is 1, j will run from 0 to 0 (all ranges of j in this answer are inclusive at both ends). The second outer iteration has i equal to 2, so j will run from 0 to 1.

    And so on, up to the final outer iteration where i is 3. In that case, j will run from 0 to 2. Had you added more iterations to the outer loop, such as:

    for (i = 1; i < somethingBiggerThanFour; i++)
    

    then you would see something like:

    Outer         4
      Inner           0
      Inner           1
      Inner           2
      Inner           3
    Outer         5
      Inner           0
      Inner           1
      Inner           2
      Inner           3
      Inner           4
    ... and so on ...
    

    In summary, you get:

    • i == 1, j == 0.
    • i == 2, j == 0, 1.
    • i == 3, j == 0, 1, 2.
    • i == 4, j == 0, 1, 2, 3.
    • i == 5, j == 0, 1, 2, 3, 4.
    • i == 6, j == 0, 1, 2, 3, 4, 5.
    • i == 7, j == 0, 1, 2, 3, 4, 5, 6.
    • i == 8, j == 0, 1, 2, 3, 4, 5, 6, 7.
    • and on and on and on, depending on the outer loop.