4

A quote from an Algorithms textbook:

"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."

So, for example, a for loop that begins with for j=1 to 3 will be executed not 3 times, but 4 times!

Question: Why would such a loop be executed 4 times and not 3 times?

By my reasoning:

When j = 1, the loop is executed. 
When j = 2, the loop is executed.
When j = 3, the loop is executed. 
When j = 4, the loop is NOT executed.

I count 3, not 4.

George
  • 6,927
  • 4
  • 34
  • 67
  • is that true, whats the book? please add reference.. – Balaji Aug 25 '15 at 11:51
  • 2
    Your reasoning is correct, but you must realize that in order to DECIDE not to execute j=4 must be tested. Consequently, there's "always" one last test that fails, making it count one more than the body-execution. "You want one more candy?" "Yes." "Ok, you want one more?" "Yes." "Ok, one more?" "No." How many questions are asked, how many candy's do you get? – Bert te Velde Aug 25 '15 at 12:17

2 Answers2

5

I think you are confused about what the statement in the book states

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.

This means that the loop condition will be tested one more time than the loop body therefore by your example:

for j = 1:3
        j = 1, pass and looped
        j = 2, pass and looped
        j = 3, pass and looped
        j = 4, failed and code executes as written
Huey
  • 5,110
  • 6
  • 32
  • 44
bnm
  • 108
  • 6
1

Here's the pseudo machine code for a for...loop

// int result = 0;
// for(int x = 0; x < 10; x++) {
//   result += x;
// }
MOV edx, 0 // result = 0
MOV eax, 0 // x = 0
.ForLoopLabel:
CMP eax, 10 // FillFlags(x - 10)
JGE .ForLoopFinishedLabel // IF x >= 10 THEN GoTo ForLoopFinishedLabel
// for loop's body
ADD edx, eax // result += x
// end of body
ADD eax, 1 // x++
JMP .ForLoopLabel // GoTo ForLoopLabel
.ForLoopFinishedLabel:
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62