Q: Which of the following use cases is best suited for a do-while loop?
-
A
Looping over an array with a known size
-
B
Repeatedly prompting user input until a valid response is given
-
C
Iterating over elements in a list
-
D
Looping through numbers from 1 to 10
B
Answer:
B
Explanation:
A do-while loop is ideal when you need to ensure that a block of code is executed at least once, regardless of the initial condition. A common use case is prompting a user for input, where you want the prompt to appear at least once before validating the input. For example, if you're asking for a non-empty string, the loop can continue prompting the user until valid input is received. Other loops like for and while may not guarantee that the prompt will appear at least once, depending on the initial condition.
Related Topic:
Share Above MCQ