The Do Statement

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: The Do Statement
Printed by: Guest user
Date: Monday, August 15, 2022, 6:20 PM

Description

The 'do-while' loop is a variation of the while loop. 'do-while' loops always execute at least once, whereas while loops may never execute.

1. The Daring do Statement

Loops are so important, and are so common in programs, that there are several Java language features for implementing them. You have already seen while loops and for loops. This chapter looks at do loops.

A programming language needs to have only one general looping method. The while statement can be used to implement any type of loop. However, as we have seen, the for statement often is convenient, and also can be used to implement any type of loop.

The do loop is occasionally convenient and can be used to implement any of the three types of loops. However, of the three looping statements, it is used the least. Some programmers prefer not to use it at all.

The do statement is not part of the AP (Advanced Placement) computer science test given to high school students in the US. It is not used in the chapters that follow this one.

Chapter Topics:

      • The do statement
      • Bottom-driven loops
      • Dangers of bottom-driven loops

Question 1:

There are several looping statements in Java, although only one (any one of them) is logically necessary.

Are there also several branching statements in Java?          Is only one of them necessary?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap35/ch35_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. The do Statement


Answer:

Yes — Java has the if statement (both with and without an else), the switch statement, and the conditional statement.

Of these, the if statement (with an else) is by far the most useful. The other two types of
branches are not logically needed, although they are sometimes useful.

The do Statement

The do statement is similar to the while statement with an important difference: the do statement performs a test after each execution of the loop body. Here is a counting loop that prints integers from 0 to 9:

Notice how the do and the while bracket the statements that form the loop body.

To start, the statements in the loop body are executed. Then the condition after the while is tested. If it is true the loop body is executed again. Otherwise, control passes to the statement after the test.

int count = 0;                      // initialize count to 0

do
{
  System.out.println( count );      // loop body: includes code to
  count++  ;                        // change the count
}
while ( count < 10 );               // test if the loop body should be
                                    // executed again.

Question 2:

Does the code fragment include the three things that all loops must do?

3. Bottom-driven Loop


Answer:

Yes.

Bottom-driven Loop

All loops must do three things:

  1. The loop must be initialized correctly.
  2. The ending condition must be tested correctly.
  3. The body of the loop must change the condition that is tested.

The code fragment includes all three, but in a different order than usual. The ending condition test is done after the loop body has executed.

int count = 0;                       // initialize count to 0

do
{
  System.out.println( count );      // loop body: includes code to
  count++  ;                        // change the count
}
while ( count < 10 );               // test if the loop body should be
                                    // executed again.         

Loops with the test at the top of the loop (while and for loops) are called top-driven loops.

Loops implemented with the test at the bottom (a do loop) are called bottom-driven loops. This location for the test has some odd (and sometimes undesirable) effects. Examine the following:

int count = 1000;

do
{
  System.out.println( count );
  count++  ;                  
}
while ( count < 10 );

Question 3:

What is the output of the revised loop?

4. Loop Body is Always Executed at Least Once


Answer:

It prints:

    1000

Loop Body is Always Executed at Least Once

Since testing is done at the bottom of the loop, the loop body must execute at least once, regardless of conditions. Java does not "look ahead" to the condition that is tested. It executes the loop body, then tests the condition to see if it should execute it again.

int count = 1000;                   // initialize

do
{
  System.out.println( count );
  count++  ;                        // change
}
while ( count < 10 );               // test  

bottomDriven

It is easy to mistakenly think that loop body will not execute even once because count starts at 1000 and the test requires count to be less than 10.

But, in fact, the loop body does execute once, printing count, and then changes it to 1001 before the test is performed. This might be a serious bug.

You will save hours of hair-tearing debugging time if you remember that

The body of a do loop is always executed at least once.

Almost always there are situations where a loop body should not execute, not even once. Because of this, a do loop is almost always not the appropriate choice.




Question 4:

(Thought question: ) Do you think that a do loop is a good choice for a counting loop?

5. User Interaction


Answer:

No. A for loop is the best choice for a counting loop.

User Interaction

The previous example used the do in a counting loop. This was to show how it worked. Usually you would use a for loop. A more appropriate use of a do is in a loop that interacts with the user.

sqrtOut

import java.util.Scanner ;
public class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    do
    {
      System.out.print("Enter a number-->");
      x = scan.nextDouble(); 
      chars = scan.nextLine();   // flush rest of the line
      System.out.println("Square root of " + x + " is " + Math.sqrt( x ) );
      System.out.print("Do you wish to continue? (yes or no) --> ");
      chars = scan.nextLine();

    }
    while ( chars.equals( "yes" ) );    

  }
}

Notice the statement that flushes the rest of the input line. This is necessary because nextDouble() reads only the characters that make up the number. The rest of the line remains in the input stream and would be what nextLine() reads if they were not flushed.


Question 5:

Examine the code. How would it be written with a while loop?

6. while Loop Version


Answer:

See below.

while Loop Version

The first iteration of the loop body can be made to happen by initializing chars to "yes." This is slightly awkward.

import java.util.Scanner;

public class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    chars = "yes" ;        // enable first iteration of the loop

    while ( chars.equals( "yes" ) )
    {
      System.out.print("Enter a number-->");
      x = scan.nextDouble(); 
      chars = scan.nextLine();   // flush rest of the line
      System.out.println("Square root of " + x + " is " + Math.sqrt( x ) );
      System.out.print("Do you wish to continue? (yes or no) --> ");
      chars = scan.nextLine();
    }

  }
}

Question 6:

Examine the code (again.) How would it be written with a for loop?

7. for Loop Version


Answer:

See below.

for Loop Version

The for loop version also seems awkward. You have to remember that the "change" part of the for statement can be omitted. This is correct syntax, but now you must be careful to make the change in the loop body.

Of course, the biggest problem with all three versions is that the user must type exactly "yes" for the program to continue. Better programs would allow "y" or "Y" or "YES" .


import java.io.* ;
public class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    for ( chars = "yes"; chars.equals( "yes" );  )  // last part of "for" omitted
    {                                               // (this is OK)
      System.out.print("Enter a number-->");
      x = scan.nextDouble(); 
      chars = scan.nextLine();   // flush rest of the line
      System.out.println("Square root of " + x + " is " + Math.sqrt( x ) );
      System.out.print("Do you wish to continue? (yes or no) --> ");
      chars = scan.nextLine();
    }

  }
}     

Question 7:

You want the program to continue when the user to enters any of the following:

    1. yes
    2. YES
    3. Y
    4. y

The program should quit for anything else. How (in general) can you do this?

8. Boolean Expression in a Condition


Answer:

The test part of the loop can use the OR operator to allow several choices.

Boolean Expression in a Condition

The test part of a loop (any of the three varieties) is a boolean expression. We want a boolean expression that evaluates to true if the user enters:

      • yes
      • YES
      • Y
      • y

and evaluates to false for anything else. Here is a near-complete expression:


while ( chars.equals( "yes" )   chars.equals( "YES" )   
        chars.equals( "y" )     chars.equals( "Y" )  )

Question 8:

Fill in the blanks.

9. Program with Alternatives


Answer:

The || (or operator) is the appropriate choice:

while ( chars.equals( "yes" ) || chars.equals( "YES" ) ||  
        chars.equals( "y" )   ||  chars.equals( "Y" )   )

Program with Alternatives


import java.util.Scanner;

public class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    chars = "yes" ;        // enable first iteration of the loop

    while ( chars.equals( "yes" || chars.equals( "YES" ) ||  
            chars.equals( "y" ) ||  chars.equals( "Y" )  )
    {
      System.out.print("Enter a number-->");
      x = scan.nextDouble(); 
      chars = scan.nextLine();   // flush rest of the line
      System.out.println("Square root of " + x + " is " + Math.sqrt( x ) );
      System.out.print("Do you wish to continue? (yes or no) --> ");
      chars = scan.nextLine();
   }

  }
}

Since any one choice is all we need, the OR operation is the appropriate way to combine the choices.

Another possiblility is to use some other methods of String: the String.toUpperCase() could convert the input to all capitals, then String.startsWith("Y") could test the first character.

The program is still not as user friendly as it could be. If the user types an invalid number in response to the prompt, an exception is thrown and the program halts and prints error messages.

Ordinary users would not like to see this. But improving the program requires the exception handling techniques discussed in chapter 100, so let's not do that now.


Question 9:

Do you wish to continue?

10. End of the Chapter


Answer:

No.

End of the Chapter

You have reached the bottom of this chapter. Click on a subject that interests you if you wish to loop back to where it is discussed.