go to previous page   go to home page   go to next page hear noise highlighting

Answer:

Yes. Now the test part of the for will look for the sentinel.


Sentinel Controlled Loop

In a sentinel controlled loop the change part depends on data from the user. It is awkward to do this inside a for statement. So the change part is omitted from the for statement and put in a convenient location.

Below is an example. The program keeps asking the user for x and printing the square root of x. The program ends when the user enters a negative number.

This program would be better if a while statement were used in place of the for statement.


import java.util.Scanner;

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

    System.out.print("Enter a value for x or -1 to exit: ")  ;
    x = scan.nextDouble();

    for (    ; x >= 0.0 ;   )  
    {
      System.out.println( "Square root of " + x + " is " + Math.sqrt( x ) ); 

      System.out.print("Enter a value for x or -1 to exit: ")  ;
      x =  scan.nextDouble();
    }
  }
}

QUESTION 13:

Do you think that the test part of a for can be omitted?


go to previous page   go to home page   go to next page