CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Writing loops within loops

There's a number of occassions when we wish to loop a number of times (and so we use a for loop) and within that loop we wish to perform another loop. While a little confusing, this construct is often quite common. It is termed a nested loop.


#define  NROWS     6
#define  NCOLS     4

for(int row = 1 ; row <= NROWS ; row = row+1) {      // the 'outer' loop

    for(int col = 1 ; col <= NCOLS ; col = col+1) {  // the 'inner' loop
        printf("(%i,%i)  ", row, col);               // print row and col as if "coordinates"  
    }
    printf("\n");                                    // finish printing on this line
}

The resulting output will be:

    (1,1)  (1,2)  (1,3)  (1,4)  
    (2,1)  (2,2)  (2,3)  (2,4)  
    (3,1)  (3,2)  (3,3)  (3,4)  
    (4,1)  (4,2)  (4,3)  (4,4)  
    (5,1)  (5,2)  (5,3)  (5,4)  
    (6,1)  (6,2)  (6,3)  (6,4)

Notice that we have two distinct loop-control variables, row and col.

Each time that the inner loop (col's loop) starts, col's value is initialized to 1, and advances to 4 (NCOLS).

As programs become more complex, we will see the need for, and write, all combinations of:

  • for loops within for loops,
  • while loops within while loops,
  • for loops within while loops,
  • and so on....

 


CITS2002 Systems Programming, Lecture 2, p14, 24th July 2024.