4. The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100.
5. Syntax for the while Statement while ( <boolean expression> ) <statement> while ( number <= 100 ) { sum = sum + number; number = number + 1; } Statement (loop body) Boolean Expression
6. Control Flow of while int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; true
7. More Examples Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. Computes the product of the first 20 odd integers. int sum = 0, number = 1; while ( sum <= 1000000 ) { sum = sum + number; number = number + 1; } 1 int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while ( number <= lastNumber ) { product = product * number; number = number + 2; } 2
9. Example: Testing Input Data String inputStr; int age; inputStr = JOptionPane.showInputDialog ( null , "Your Age (between 0 and 130):" ) ; age = Integer.parseInt ( inputStr ) ; while ( age < 0 || age > 130 ) { JOptionPane.showMessageDialog ( null , "An invalid age was entered. Please try again." ) ; inputStr = JOptionPane.showInputDialog ( null , "Your Age (between 0 and 130):" ) ; age = Integer.parseInt ( inputStr ) ; } Priming Read
10. Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to Meaning Usage Operator a = a % b; a %= b; %= a = a / b; a /= b; /= a = a * b; a *= b; *= a = a – b; a -= b; -= a = a + b; a += b; +=
11.
12. Loop Pitfall - 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 int product = 0; while ( product < 500000 ) { product = product * 5; } 1
13.
14. Loop Pitfall - 2 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count != 1.0f ) { count = count + 0.33333333f; } //eight 3s 2 float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; } //seven 3s 1
15. Loop Pitfall – 2a int result = 0; double cnt = 1.0; while ( cnt <= 10.0 ){ cnt += 1.0; result++; } System.out.println ( result ) ; 1 int result = 0; double cnt = 0.0; while ( cnt <= 1.0 ){ cnt += 0.1; result++; } System.out.println ( result ) ; 2 Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. 10 11
16.
17. The do - while Statement int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= 1000000 ); These statements are executed as long as sum is less than or equal to 1,000,000.
18. Syntax for the do - while Statement do <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= 1000000 ) ; Statement (loop body) Boolean Expression
19. Control Flow of do - while int sum = 0, number = 1 sum += number; number++; sum <= 1000000 ? true false
20.
21. Example: Loop-and-a-Half Control String name; while ( true ){ name = JOptionPane.showInputDialog ( null , "Your name" ) ; if ( name.length () > 0 ) break ; JOptionPane.showMessageDialog ( null , "Invalid Entry." + "You must enter at least one character." ) ; }
22.
23.
24. Example: Confirmation Dialog boolean keepPlaying = true ; int selection; while ( keepPlaying ){ //code to play one game comes here // . . . selection = JOptionPane.showConfirmDialog ( null , "Play Another Game?" , "Confirmation" , JOptionPane.YES_NO_OPTION ) ; keepPlaying = ( selection == JOptionPane.YES_OPTION ) ; }
25. The for Statement int i, sum = 0, number; for ( i = 0; i < 20; i++ ) { number = scanner.nextInt ( ) ; sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, … , 19 ).
26. Syntax for the for Statement for ( <initialization>; <boolean expression>; <increment> ) <statement> for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } Initialization Boolean Expression Increment Statement (loop body)
27. Control Flow of for i = 0; false number = . . . ; sum += number; true i ++; i < 20 ?
28. More for Loop Examples i = 0, 5, 10, … , 95 j = 2, 4, 8, 16, 32 k = 100, 99, 98, 97, ..., 1 for (int i = 0; i < 100; i += 5) 1 for (int j = 2; j < 40; j *= 2) 2 for (int k = 100; k > 0; k--) ) 3
29.
30. Generating the Table int price; for ( int width = 11; width <=20, width++ ){ for ( int length = 5, length <=25, length+=5 ){ price = width * length * 19; //$19 per sq. ft. System.out.print ( “ “ + price ) ; } //finished one row; move on to next row System.out.println ( “” ) ; } INNER OUTER
46. The Logic of playGame int guessCount = 0; do { get next guess ; guessCount++; if ( guess < secretNumber ) { print the hint LO ; } else if ( guess > secretNumber ) { print the hint HI ; } } while ( guessCount < number of guesses allowed && guess != secretNumber ) ; if ( guess == secretNumber ) { print the winning message ; } else { print the losing message ; }
47.
48.
49.
50.
51.
52.
Notas del editor
We will study two forms of repetition statements in this lesson. They are while and do-while statement.
In Chapter 5, we studied selection control statements. We will study in this chapter the second type of control statement, a repetition statement, that alters the sequential control flow. It controls the number of times a block of code is executed. In other words, a block of code is executed repeatedly until some condition occurs to stop the repetition. There are fundamentally two ways to stop the repetition—count-controlled and sentinel-controlled.
The first repetition control we will study is the while statement. Here’s an example that computes the sum of integers from 1 to 100, inclusively. Note: there’s a closed form to compute the sum of 1 to 100, which is (100 * 101) / 2, so this repetition statement is a illustration purpose only.
Here’s the general syntax of a while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body may not be executed at all.
This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement.
Variation on computing the product of the first 20 odd integers: int product = 1, number = 1, lastTerm = 20, count = 1; while ( count <= lastTerm ) { product = product * (2 * number – 1); count = count + 1; }
Here's a more practical example of using a repetition statement. This code will only accept a value greater than 0 but less than 130. If an input value is invalid, then the code will repeat until the valid input is read. Notice that the 'age' variable must have a value before the boolean expression of the while statement can be evaluated. We therefore read the input value before the while test. This reading of input values before the test is called priming read. The loop body of this while statement is executed zero times if the input is valid the first time.
When writing a repetition statement, we often see the statement that modifies the value of a variable in the form such as sum = sum + number. Because of a high occurrence of such statement, we can use shorthand operators. These shorthand assignment operators have precedence lower than any other arithmetic operators, so, for example, the statement sum *= a + b; is equivalent to sum = sum * (a + b);
If you are not careful, you can easily end up writing an infinite loop. Make sure the test is written in such a way that the loop will terminate eventually.
When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.
Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/3.0 + 1.0/3.0 + 1.0/3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision.
Here's another example of using a double variable as a counter. The two loops are identical in concept, and therefore, should output the same result. They would if real numbers are stored precisely in computer memory. Because the value of 0.1 cannot be represented precisely in computer memory, the second one will actually print out 11, while the first one prints out 10, as expected.
Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop.
Here's an example of the second type of repetition statement called do-while. This sample code computes the sum of integers starting from 1 until the sum becomes greater than 1,000,000. The main difference between the while and do-while is the relative placement of the test. The test occurs before the loop body for the while statement, and the text occurs after the loop body for the do-while statement. Because of this characteristic, the loop body of a while statement is executed 0 or more times, while the loop body of the do-while statement is executed 1 or more times. In general, the while statement is more frequently used than the do–while statement.
Here’s the general syntax of a do-while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body is executed at least once.
This flowchart shows the control flow of the do-while statement. If the <boolean expression> is true, the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this do-while statement.
This is a simple example of a loop-and-a-half control. Notice the priming read is avoided with this control.
Here's an example of how we can use a confirmation dialog in a loop. At the end of the loop, we prompt the user to repeat the loop again or not.
This is a basic example of a for statement. This for statement reads 20 integers and compute their sum.
This shows the general syntax for the for statement. The <initialization> component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i < 10; i++) instead of int i; for (i = 0; i < 10; i++)
Here are some more examples of a for loop. Notice how the counting can go up or down by changing the increment expression accordingly.
Just an if statement can be nested inside another if statement, we often nest for loops. For example, using a nest-for loop is the most appropriate way to generate a table such as the illustration.
Here's how the table can be produced by a nested-for loop. For each value of width, length will range from 5 to 25 with an increment of 5. Here’s how the values for width and length change over the course of execution. width length 11 5 10 15 20 25 12 5 10 15 20 25 13 5 10 and so on…
We can achieve the same result by using the currentTimeMillis method of the System class as long start = System.currentTimeMillis(); //code to measure long end = System.currentTimeMillis(); long elapsedTimeInMilliSec = end – start; To get the elasped time in seconds, we divide the milliseconds by 1000 long elapsedTimeInSec = elapsedTimeInMilliSec / 1000;
As a part of the overall plan, we begin by identifying the main tasks for the program. Unlike the overall plan for the previous sample developments, we will use a pseudo code to express the top level logic of the program.
The structure of this program is very simple. We will use two standard classes, one for input and output and another for generating random numbers.
The second and the third steps correspond to the two major tasks identified in the overall plan.
In the first step, we determine a little more detailed control logic than the one stated in the overall plan. For each of the five identified functions, we will define a method: describeRules, generateSecretNumber, playGame, and prompt.
Please use your Java IDE to view the source files and run the program.
Run the program and verify that the topmost control loop is functioning correctly.
In order to verify whether our code is working correctly or not, we need to know what is the secret number. The easiest way to do this is to use a fixed number, such as 45, make the temporary generateRandomNumber to return this fixed number.
Here's the playGame method expressed as a pseudocode.
We implement the playGame and getNextGuess methods in this step.
We need to verify the correctness of two methods: playGame and getNextGuess. Try all cases presented here and confirm that you get the expected responses.
Notice that we have one temporary statement to output the value of secretNumber. We include it for the testing purpose, i.e., we need to check the numbers generated are valid.
As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count < N && 1 <= number && number <= 100 ); if ( number < 1 || number > 100 ) { System.out.println(&quot;Error: &quot; + number); } else { System.out.println(&quot;Okay&quot;); } } }