Java MCQ: Which loop construct in Java is best suited when the number of iterations is unknown?
Answer:
Explanation:
The while
loop in Java is best suited for scenarios where the number of iterations is unknown or depends on a certain condition. The loop continues to execute as long as the specified condition remains true. The condition is evaluated before each iteration, allowing the loop to terminate when the condition becomes false.
For example, consider the following while
loop:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
In this loop, the number of iterations is determined by the condition i < 10
. The loop will continue to execute until i
reaches 10, at which point the condition becomes false, and the loop terminates.
The while
loop is particularly useful in cases where the loop’s execution depends on dynamic factors, such as user input or the state of a variable that may change during the loop’s execution.
Reference links:
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html