Which type of loop is guaranteed to have the body execute at least once?

Which type of loop is guaranteed to have the body execute at least once?

A. do-while loop

B. for (traditional)

C. for-each

D. while

Answer:

A. do-while loop

Explanation:

A do-while loop checks the loop condition after execution of the loop body. This ensures it always executes at least once, and Option A is correct. 

Option B is incorrect because there are loops you can write that do not ever enter the loop body, such as for (int i=0;i<1;i++). 

Similarly, Option D is incorrect because a while loop can be written where the initial loop condition is false. 

Option C is incorrect because a for-each loop does not enter the loop body when iterating over an empty list.


Comments