Skip to main content
ICT
Lesson A12 - Iterations
 
Main   Previous Next
 

F. The do-while Loop (Optional) page 8 of 18

  1. There are conditional looping situations where it is desirable to have the loop execute at least once, and then evaluate an exit expression at the end of the loop.

  2. The do-while loop allows you to do a statement first, and then evaluate an exit condition. The do-while loop complements the while loop that evaluates the exit expression at the top of the loop.

  3. The general form of a do-while loop is:

    do
    {
      statement;
    }
    while (expression);
  4. The flow of control for a do-while loop is illustrated:

  5. The following fragment of code will keep a running total of integers, terminated by a sentinel zero value.

    int number, total = 0;
    do
    {
      System.out.print("Enter an integer (0 to quit) --> ");
      number = in.readInt();
      total += number;
    }
    while (number != 0);

    In contrast to the while loop version, the do-while has the advantage of using only one input statement inside of the loop. Because the Boolean condition is at the bottom, you must pass through the main body of a do-while loop at least once.

  6. The same strategies used to develop while loops apply to do-while loops. Make sure you think about the following four sections of the loop: initialization, loop boundary, contents of the loop, and the state of variables after the loop.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.