Do-While Loops

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

A do-while loop is similar to a while loop, except that the conditional statement and the boolean test is done at the bottom of the loop. This can be more natural in some cases, but the do-while loop is perhaps not as frequently used as the while loop, since with a little manipulation, any do-while loop can be written as a regular while loop.

Syntax

 do { 
   stmts;
} while (boolExpr); 

Note that there is a semicolon after the boolean expression.

One important point to note about do-while loops is that the loop will always execute once: the boolean condition is not tested until the bottom of the loop, 'after the loop body has been executed once. This may make things easier in some cases, but it may not be what you want in other cases. Make sure that if you're using a do-while loop, it makes sense that the code inside the loop is executed at least once.

Example: Waiting for valid user input

Here's an example which repeatedly asks the user for input until the input is a positive number:

 int userInput;
Scanner keyboard= new Scanner(System.in); 

do { 
   
   System.out.print("Please enter a positive integer to continue:");
   userInput = keyboard.nextInt();

} while (userInput <= 0); 

Notice that the loop doesn't need to be primed like a while loop, since the test is not done at the top of the loop, only at the bottom. A full execution of the body of the loop will always be completed before the test condition is ever checked.


Unrolling Do-While Loops

While you can use do-while loops in COMP 1010, some people prefer not to read them or write them in their code. One explanation offered for this is that when reading code top-to-bottom, it isn't obvious what a do-while loop does when you arrive at it: there's no explanation of the loop condition, and it can be difficult to search through the code to find the end of the while loop.

Luckily, we can unroll do-while loops and replace them with a while loop which has been properly primed. For instance, the do-while loop from the first example:

 String input;
int userInput;
do { 
   input = JOptionPane.showInputDialog("Enter a positive integer");
   userInput = Integer.parseInt(input);
} while (userInput <= 0); 

Can be rewritten as a while loop:

 String input;
int userInput;

input = JOptionPane.showInputDialog("Enter a positive integer");
userInput = Integer.parseInt(input);

while (userInput <= 0) { 
   input = JOptionPane.showInputDialog("Enter a positive integer");
   userInput = Integer.parseInt(input);
} 

To convert a do-while loop to a while loop, you need to:

  1. Take the entire body of the loop and paste it before the new while loop.
  2. Take the conditional expression from the end of the do-while loop and place it at the top of the while loop.
Previous Page: While Loops Next Page: Do-While Loops