Completion requirements
The 'for' loop is more compact than the 'while' and 'do' loops and automatically updates the loop counter at the end of each iteration. Both 'for' and 'while' loops are designed for different situations. You'll learn more about when to use each later.
13. Sentinel Controlled Loop
Answer:
Yes. Now the test part of thefor
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?