When is a do-while the better choice over other types of loops? What are some common scenarios where its better than others?
I understand the function of a do-while, but not when to use it.
Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.
Simply, when you want to check condition before and then perform operation while is better option, and if you want to perform operation at least once and then check the condition do-while is better. Show activity on this post.
The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.
The test of the termination condition is made after each execution of the loop; therefore, a do-while loop executes one or more times, depending on the value of the termination expression. The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body.
When you need something done at least once, but don't know the number of times prior to initiating the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With