The do-while loop

  • Syntax of the do-while-statement in Java:

       do
           one-statement;  // Loop body
       while ( loop-contuation-condition )  ;   // must end with ; 
    
    or:
    
       do
       { // Loop body
           statement1;
           statement2;
           ...
       } while ( loop-contuation-condition )  ;  // must end with ; 

  • Effect of the do-while statement:

    1. Execute the loop body

    2. Check the loop-contuation-condition

    3. If true:   repeat
      If false, continue with the next statement in the program

The do-while loop    Flow chart

     do
     { // Loop body
       statements(s);
     } while ( loop-contuation-condition )  ; 

  • The flow chart of the do-while statement is:

The do-while loop    Example

  • Use a do-while loop:

      • Write a program that read a list of (positive) integer numbers until 0 and print their sum

  • Plan for the program:

        sum = 0
      
        repeat:
        {
           x = read next number; 
      
           if ( x != SENTINEL )  // SENTINEL == 0
              sum = sum + x;
      
        } as long as: (x != SENTINEL)
      

The do-while loop    Example

  • Solution in Java:

        Scanner input = new Scanner(System.in);
            
        int sum = 0;
        int x = -1;
            
        do
        {
           System.out.print("Enter an integer (ends if it is 0): ");
           x = input.nextInt();
               
           if ( x != 0 )
              sum = sum + x;
        } while ( x != 0 );
            
        System.out.print(sum);
      

DEMO: demo/05-loops/03-do-while/ReadAndSum.java

Comment

 

  • The do-while loop is rarely used by programmers

  • The most useful loop statements in any programming language are:

      • The while loop

      • The for loop that we will discuss next