Looping Variables End Value

I received a question on a looping variable and why its value after the loop isn’t the same as the ending value of the loop. It’s a puzzling issue I remember from when I first learned to program, but one that you can understand once you figure out what the loop does.

As an example, consider a basic for loop, such as the one shown in the following code:

#include <stdio.h>

int main()
{
    int i;

    for(i=0;i<10;i++)
        printf("The value of 'i' is %d\n",i);

    printf("And after the loop, 'i' is %d\n",i);

    return(0);
}

The for loop repeats 10 times. Variable i measures the count, starting at i=0 and looping 10 times — as long as the value of i is less than 10, or i<10.

So the loop stops when?

It stops when the value of i is 10 or greater. Therefore, after the loop is complete, the value of i isn’t equal to 9, rather it’s equal to 10 or greater. Here’s the output:

The value of 'i' is 0
The value of 'i' is 1
The value of 'i' is 2
The value of 'i' is 3
The value of 'i' is 4
The value of 'i' is 5
The value of 'i' is 6
The value of 'i' is 7
The value of 'i' is 8
The value of 'i' is 9
And after the loop, 'i' is 10

The only time this effect is confusing is when you forget that the counter does increment one last time when the loop doesn’t repeat. So at the top of the loop (the for statement), variable i is equal to 10. Then the loop skips and the next statement is processed.

The same effect holds true when you plow through an array or a string. The last time the loop tries to execute, the counter variable is one greater than what was specified. So if the loop ends on the \0 (null character) at the end of a string, the pointer is still referencing that character after the loop is done. That is:

while(ch != '\0')

The above loop stops when ch contains (or points at) the character \0.

The key to understanding this effect, is to slowly digesting the individual pieces of a loop, specifically the counter variables. Never assume that the variable is anything after the loop is complete until you look at the looping statement. When you’re in doubt, add a test statement in the code (such as the one in the example) to demonstrate to yourself what the ending counter variable value really is.

Leave a Reply