Why are loops executed one more time than the loop body?

喜夏-厌秋 提交于 2019-12-07 15:24:40

问题


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.


回答1:


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



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!