Do-While Loops

From CompSciWiki
Revision as of 08:03, 4 September 2008 by Mdomarat (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

The do-while loop is similar to a while loop, except that the condition is tested at the bottom of the loop.

   

{{{Body}}}

A do-while loop is similar to a while loop, except that the boolean test is done at the bottom of the loop. This can be more natural in some loops, but the do-while loop is perhaps not as frequently used as while loops, since with a little manipulation, you can rewrite any do-while loop 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

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

String inp;
int userInp;
do { 
   inp = JOptionPane.showInputDialog(null,"Enter a positive integer");
   userInp = Integer.parseInt(inp);
} while (userInp <= 0);