CSCI 1301

do-while Loop

1. Learning Objectives

  • What is a do-while loop?
  • What is the difference between do-while and while loop?

2. do-while Loop

do-while loop is a loop statement that is guaranteed to execute at least 1 time. Unlike while loop that checks loop control variable before executing its body, do-while loop executes the loop body then checks whether looping should continue. This order of operation guarantees at least one execution of the loop body will occur.

do-while does not exist in all programming languages. In its absence you can implement the same behavior using a while loop. However, if a programming language includes a do-while loop, it may reduce the number of commands needed to implement required behavior.

3. Syntax

3 // loop body here
4 // update control variable
6} while(booleanExpression);
  • do-while loops starts with keyword do followed by loop body (in brackets)
  • the while keyword and Boolean expression occur after the loop body
  • notice there is a semicolon at the end

The example below shows how to display numbers 1-10 using a do-while loop:

4. Terminating do-while Loop

When implementing a do-while loop, you must choose a termination strategy, which include:

  • using a counter variable to iterate n times
  • using a break statement
  • using a flag variable

You can find an explanation and example of each strategy here.

5. Comparing while and do-while

When deciding whether to use a while or do-while loop, first ask: is there some behavior that should always execute at least once? If the answer is yes, do-while maybe preferable option. If the answer is no, choose a while loop. Apart from this edge case, you can implement the same behavior using both looping structures, but one maybe better suited than the other.

6. Summary

What is a do-while loop?

do-while is a looping statement that continues to execute indefinitely until the loop condition becomes false or break keyword is encountered.

What is the difference between do-while and while loop?

  • do-while loop will execute its body 1...N times
  • while loop will execute its body 0...N times