Website by Joshua Bleier

Module 2.2 - For Loops & Nested Loops

Let's take a closer look at the inner for loop in 2nestedfor.c from the connect section:

16
  for (j = 0; j < m ; j++) {
17
    printf("\tinner loop %d of %d\n", j + 1, m);
18
  }

As mentioned in the connect section, we purposefully initialize j as 0; to make sure that we only only iterate m times, we compensate within the conditional test by continuing to loop only while j < m, not for j <= m as we would if j was initialized as 1.

In addition, to show the true loop count in the printf statement, we print j + 1 rather than j, so that the print-out shows the loop going from 1 to m, rather than 0 to m - 1.

We introduce all of this to prepare you for our module on arrays, where we access variables stored in an m-element array from 0 to m - 1, rather then from 1 to m.

But what if we messed up on our iterations (Say, by looping from 0 to m)? In the above example, the results would be fairly innocuous; the program would simply print out the following (If the user input 8 for the inner loop m value):

inner loop 9 of 8

However, if the for loop instead incorporated a sequential assignment of values into the array, then once we got to the last iteration, j = m, we would be attempting to assign a value into an area of memory in the computer not allocated for the array (Remember, an array of 8 values will start at 0, and go to 7). The program would overwrite a potentially critical portion of memory, and would likely cause the program to crash.

And, just as the missing semi-colon is likely to trip you up occassionally and lead to compilation errors, this "off-by-one" error is highly likely to cause strange program behavior, or program crashes, when dealing with array elements.

In the future, when you're debugging a misbehaving or crashing program, you'll be doing yourself a favor by looking for an off-by-one error early in the debugging process.

 

Continue to the Extend Section ->