do-while loop

6.10 do-while loop

SYNTAX

do {
    
statements ;
} while(
condition);

OR

do
statement ;
while (
condition) ;

PROGRAM FLOW

  1. The statement(s) are executed.
  2. The boolean expression condition is evaluated. If condition evaluates as true, then flow returns to step 1.

EXAMPLE

The following example uses iteration to find an approximate solution to x=f(x). The user must specify the function f(x), a starting point x1 and a precision prec > 0. The loop computes x2 = f(x1). If |x2-x1| is smaller than prec, the loop replaces x1 by x2 and terminates. Otherwise it replaces x1 by x2 and repeats. To trap infinite loops, a count is kept of the number of iterations. The loop also terminates if the count exceeds a specified count_limit.
        int count = 0 ;
        int count_limit = 1000 ;
        double error, x2 ;
        
        do {
             x2 = f(x1) ;
             error = Math.abs(x2-x1) ;
             x1 = x2 ;
             count++ ;
        } while ( (error > prec) && (count < count_limit) )  ;

COMMON ERRORS

Don't forget the semicolon after the condition.
Next 6.11 while loop

David Maxwell, who is still writing this, would like to hear your comments and suggestions.