Presentation is loading. Please wait.

Presentation is loading. Please wait.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 1 Chapter 6 Repetition Statements.

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 1 Chapter 6 Repetition Statements."— Presentation transcript:

1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 1 Chapter 6 Repetition Statements

2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 2 Definition Often need to execute block of code multiple times –Repetition statements (loops) are used for this Loop termination controlled by a Boolean expression –Counting loops execute a fixed number of times. –Sentinel loops terminate on encountering a sentinel value Java has three loop structures

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 3 Pre-Test loop int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; true

4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 4 while ( number <= 100 ) { sum = sum + number; number = number + 1; } Syntax for the while Statement while ( ) Statement (loop body) Boolean Expression

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 5 Some 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

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 6 String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); while (age 130) { JOptionPane.showMessageDialog(null, "Invalid age : Please try again."); inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); } Example: Testing Input Data Priming Read

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 7 Common Loop Pitfalls infinite loops : control expression can never be false –no change is made to the variables in the control expression –the control expression is too restrictive off-by-one errors : one too many or one too few iterations of the loop

8 Examples of Infinite loops 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

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 9 Overflow An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. –For float and double, a value that represents infinity is assigned to the variable. –For int, the value “wraps around” and becomes negative.

10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 10 Round-off Errors -> Infinite Loops 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

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 11 Round-off Errors -> Off-By-One Errors 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

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 12 Off-by-One Errors Goal: Execute the loop body 10 times. count = 1; while ( count < 10 ){... count++; } 1 count = 0; while ( count <= 10 ){... count++; } 3 count = 1; while ( count <= 10 ){... count++; } 2 count = 0; while ( count < 10 ){... count++; } 4 13 andexhibit off-by-one error.

13 Post-Test Loop int sum = 0, number = 1 sum += number; number++; sum <= 1000000 ? true false

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 14 do { sum += number; number++; } while ( sum <= 1000000 ); Syntax for the do-while Statement do while ( ) ; Statement (loop body) Boolean Expression

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 15 Counting Loop i = 0; false number =... ; sum += number; true i ++; i < 20 ?

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 16 for (i = 0; i < 20; i++ ) { number = scanner.nextInt(); sum += number; } Syntax for the for Statement for ( ; ; ) Initialization Boolean Expression Increment Statement (loop body)

17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 17 for Loop Examples for (int i = 0; i < 100; i += 5) 1 i = 0, 5, 10, …, 95 for (int j = 2; j < 40; j *= 2) 2 j = 2, 4, 8, 16, 32 for (int k = 100; k > 0; k--) ) 3 k = 100, 99, 98, 97,..., 1

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 18 Nested Loops can be nested We can use nested loops to generate tables for (int i=1; i<=10; i++) { for (int j=1; j<=10; j++) System.out.print(i * j + "\t"); System.out.println(); } How many times does the loop execute? –The inner loop executes 10 times for each value of i

19 Input Loops We often need to read an unknown number of values of a particular type. –How do you know when to stop? The Scanner class has a set of methods for determining what comes next in the input –boolean hasNext() –boolean hasnextLine() –boolean hasNextInt() –boolean hasNextDouble()

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 20 Iteration using Recursion Some mathematical functions are defined recursively n! = n * (n-1) * (n-2) * … * 2 * 1 A recursive method is one that calls itself int factorial ( int n) { if (n<=1) return 1; else return n * factorial( n-1); } Recursion is generally less efficient than loops so use it only when you need to

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 21 Finding GCD

22 Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6. From Java 5.0, we can use the Formatter class. System.out (PrintStream) also includes the format method.

23 The Formatter Class We use the Formatter class to format the output. First we create an instance of the class Formatter formatter = new Formatter(System.out); Then we call its format method int num = 467; formatter.format("%6d", num); This will output the value with the field width of 6.

24 The format Method of Formatter The general syntax is format(,,,... ) Example: int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3);

25 The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format("%6d", 498); is equivalent to System.out.format( "%6d", 498 );

26 Control Strings Integers % d Real Numbers %. f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class.


Download ppt "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 6 - 1 Chapter 6 Repetition Statements."

Similar presentations


Ads by Google