next up previous
Next: Example of a do Up: Unit 06 Previous: The do loop

Observations on the do loop

Since the condition of end of loop is evaluated only after the body of the loop has been executed, it follows that:

Example: Sum integers read from input until a 0 is read.

int i;
int sum = 0;
do {
  i = Integer.parseInt(JOptionPane.showInputDialog(
                         "Input an integer (0 to terminate)"));
  sum = sum + i;
} while (i != 0);
System.out.println("sum = " + sum);

Note that the syntax of the do statement requires that there is a 't' after  while (condition). To increase readability of the program, and in particular to avoid confusing the   while (condition);   part of a do loop with a while statement with empty body, it is in any case better to include the body of the do loop in a block, and indent the code as follows (as shown also in the example above):

do {
  statement
} while (condition);


next up previous
Next: Example of a do Up: Unit 06 Previous: The do loop