Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a For Loop always executed at least once?

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 <=5; i++) {
    //irrelevant for this question
}

According to her, this loop would execute at least once, yet it does not, or am I missing something? Is there any case, no matter what language, where this would execute once? To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

like image 341
Klaus9090 Avatar asked Jul 05 '17 17:07

Klaus9090


People also ask

Is for-loop always executes at least once?

A for-loop always makes sure the condition is true before running the program. Whereas, a do-loop runs the program at least once and then checks the condition. Show activity on this post. An entry controlled loop will never execute if the condition is false , however, exit controlled loop will execute at least once.

In which loop loop is executed at least once?

The 'do-while' loop is a variation of the while loop. 'do-while' loops always execute at least once, whereas while loops may never execute.


2 Answers

You could say a for-loop is always evaluated at least once.

But if a for-loop's condition is not met, its block will never execute.

Because you didn't ask about other loops, I won't address those.

like image 115
NonCreature0714 Avatar answered Sep 22 '22 06:09

NonCreature0714


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.

like image 33
NathanOliver Avatar answered Sep 23 '22 06:09

NathanOliver