What Do You Use a "do While" Loop for in Programming?


Quick Answer

A do while loop is used to carry out a certain action (the do) as long as a certain condition is true (the while). For example, a do while statement could be used to increment a variable by one while that variable is less than 10. As soon as the variable is 10 or greater, the do while loop ends and the code progresses to the next section.

Continue Reading
Related Videos

Full Answer

It is important to note that a do while loop performs its action at least once since the do statement comes before the while statement. This is in contrast to a while loop that may not perform the action at all if the while condition is already false. Using the above example, if the variable is already equal to 10, then a while loop does not execute any code, whereas a do while loop first increments the variable to 11, and then terminates when it reaches the while condition.

As with other programming control structures, it is possible for a do while loop to get stuck in an infinite loop if the while condition always evaluates to true. This is sometimes done intentionally and is usually paired with another control structure, such as a break statement, to terminate the loop.

Learn more about Computer Programming

Related Questions