Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Nested loops using for loops


1. Nested loops using for loops
Nested loops are here presented using for loops. See Nested loops using while loops for the same loop discussion using while loops.

2. Counting
Most people start counting at 1. Most computer people start counting at 0.

3. Nested loops
Nested loops are loops within loops. A nice way to think about nested loops is with a rectangular set of blocks arranged into rows and columns.

Let X represent one block. Here is a depiction of 12 blocks arranged into 3 rows and 4 columns.
X X X X X X X X X X X X

We can process these blocks in row-major order or column-major order. (Or some other order).

4. Numbering
Most people think of the block orderings as follows.
. 1 2 3 4 1 X X X X 2 X X X X 3 X X X X

Computer people
. 0 1 2 3 0 X X X X 1 X X X X 2 X X X X


5. Row major order code
Row-major order processes the rows in the outer loop and columns in the inner loop.

Here is the C code.


6. Row major order output
Here is the output of the C code.


7. While loop comparison
Here as a while loop for comparison.

Here is the C code.


8. Row major order output
Here is the output of the C code.


9. Column major order code
Column-major order processes the columns in the outer loop and rows in the inner loop.

Here is the C code.


10. Column major order output
Here is the output of the C code.


11. While loop comparison
Here is the C code.


12. Column major order output
Here is the output of the C code.


13. End of page