Discuss a situation in which it would be more appropriate to use a do…while statement than a while statement. Explain why.
What will be an ideal response?
If you want a statement or set of statements to execute at least once, then repeat based on a condition, a do…while is more appropriate than a while (or a for). A do…while statement tests the loop-continuation condition after executing the loop’s body;
therefore, the body always executes at least once. A while tests the loop-continuation
condition before executing the loop’s body, so the application would need to include
the statement(s) required to execute at least once both before the loop and in the body of the loop. Using a do…while avoids this duplication of code. Suppose an application needs to obtain an integer value from the user, and the integer value enteredmust be positive for the application to continue. In this case, a do…while’s body could contain the statements required to obtain the user input, and the loop-continuation condition could determine whether the value entered is less than 0. If so, the loop would repeat and prompt the user for input again. This would continue until
the user entered a value greater than or equal to zero. Once this criterion was met, the
loop-continuation condition would become false, and the loop would terminate, allowing the application to continue past the loop. This process is often called validating input.
You might also like to view...
A double table is a table inside the cell of another table
Indicate whether the statement is true or false
With a determinate loop, you do not know the number of iterations ahead of time.
Answer the following statement true (T) or false (F)
A game console is small enough to fit in one hand, making it more portable than the handheld game device.
Answer the following statement true (T) or false (F)
A(n) _________ is a piece of malware that, by definition, gains privileged access to a computer.
Fill in the blank(s) with the appropriate word(s).