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:


The "do-while" loop is guaranteed to have the body execute at least once. This is because the condition that controls the loop is checked at the end of each iteration, not the beginning as in "while" or "for" loops. 

Here's an example in Java:
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 10);
In this example, the loop will print the value of i, and then increment i by 1, as long as i is less than 10. Even if the condition is not met initially (e.g., if i starts as 10), the body of the loop will still execute once before the condition is checked.

Comments