



























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




























These statements are executed as long as number is less than or equal to 100.
while (
Direct Approach More Efficient Approach
int age; Scanner scanner = new Scanner(System.in); System.out.print("Your Age (between 0 and 130): "); age = scanner.nextInt( ); while (age < 0 || age > 130 ) { System.out.println( "An invalid age was entered. Please try again."); System.out.print("Your Age (between 0 and 130): "); age = scanner.nextInt( ); }
Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; }
int product = 0; while ( product < 500000 ) { product = product * 5; }
o An infinite loop often results in an overflow error. o An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. o In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value. Overflow
int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result);
int result = 0; double cnt = 0.0; while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result);
Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.
count = 1; while ( count < 10 ){
... count++; }
count = 0; while ( count <= 10 ){
... count++; }
count = 1; while ( count <= 10 ){
... count++; }
count = 0; while ( count < 10 ){
... count++; }
do
o Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body. o It is implemented by using reserved words while, if, and break. Loop-and-a-Half Repetition Control