Java MCQ: Which loop construct in Java is best suited when the number of iterations is known?
Answer:
Explanation:
The for
loop in Java is best suited when the number of iterations is known beforehand. This loop is ideal for scenarios where the exact number of times a block of code needs to execute is predetermined. The for
loop provides a clear and concise structure that includes the initialization of the loop variable, the condition for continuing the loop, and the increment or decrement operation, all in one line. This structure makes it easy to control the number of iterations and is particularly useful in situations like iterating over arrays, executing a block of code a specific number of times, or when counting down or up through a sequence.
For example, consider the following for
loop:
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This loop will execute exactly 10 times, printing the values from 0 to 9. The number of iterations is predetermined, making the for
loop the best choice for such scenarios.
Reference links:
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html