Answer:

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

User Interaction

The example used the do in a counting loop. This was to show how it worked. Usually you would use a for loop. A better application of a do is where the user is asked if the program should continue after each iteration of a loop.

import java.util.Scanner ;
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. Here is how the program works:

dos window

QUESTION 5:

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