Why does the "for" loop execute one more time than the body of the loop?

Question:

In the book Introduction to Algorithms, there is a line under the heading Analysis of Insertion Sort that reads:

"When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body."

The for loop, as far as I understand, uses a counter for the iterating variable. So, for example, by executing the code:

for j in range(0,3):
     print(j)

in python, we get the result:

0
1
2

The iterating variable j only goes through the values 0, 1 and 2. So the for loop and the body of the loop both execute only thrice.

A similar question has been asked here: Why are loops executed one more time than the loop body?

However, I reckon that the OP confused the mechanism of for loop with while loop. The answers to the question seem to support his misconception.

Answers:

In your Python example, do_something() in the loop

for j in range (0,n):
    do_something()

is executed n-1 times because the upper bound of the range is non-inclusive. So it will be executed when j=0, j=1, … j = n-1. The loop itself will execute one more time (i.e. when j=n) and see that the value is no longer in range and will not execute the body.

So that is why the for-loop executes one more time than the body.

The same reasoning applies to for loops of course.

Answered By: Matti

That is because there is always one more evaluation of the condition of the loop than there are executions of the body of the loop.
Take this simple example:

x = 4
while x < 0:
    x += 1
    print('hello')

We can see that the body of the loop is never executed (0 times), while the exit condition of the loop is evaluated once(1 time).
So, in any situation, we have the following:
The body of the loop is executed once for every time the condition is evaluated to True
AND
The condition is one more time evaluated to False, for the program to exit the loop.

Answered By: m.raynal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.