Is a For Loop always executed at least once?

前端 未结 4 1758
栀梦
栀梦 2021-02-20 01:32

According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

for (int i=6; i &         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 02:09

    A loop will only execute while its condition is true. Since a for loop and a while loop both check the condition before the body is executed they will never execute if the condition is false.

    The only loop that will is a do while loop. With a do while loop the condition is not evaluated until the end of the loop. Because of that a do while loop will always execute at least once.

提交回复
热议问题