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.
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
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:
来源:https://stackoverflow.com/questions/32202655/why-are-loops-executed-one-more-time-than-the-loop-body