Which loop construct guarantees that the loop body is executed at least once?

Java MCQ: Which loop construct guarantees that the loop body is executed at least once?

a) for loop
b) while loop
c) do-while loop
d) continue statement

Answer:

c) do-while loop

Explanation:

The do-while loop in Java guarantees that the loop body is executed at least once, regardless of the condition. This is because the condition is checked after the loop body has been executed. This loop is particularly useful for scenarios where the loop body must be executed at least once, even if the condition is false.

For example, consider the following do-while loop:


int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 0);

In this example, the loop body will execute once, printing 0, even though the condition i < 0 is false. After the first iteration, the loop will terminate because the condition is false.

The do-while loop is useful when the loop body must be executed at least once before any condition check is performed.

Reference links:

https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top