Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.

Similar presentations


Presentation on theme: "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement."— Presentation transcript:

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement assignment operators  Repetition while do-while for

2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  Updating a variable by adding or subtracting 1 is a very common operation i = i + 1; j = j - 1;  Java has operators that allow you to write this more compactly i++ and ++i for incrementing j-- and --j for decrementing  Both operators can come either before (prefix) or after (postfix) the operand.

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  In a statement by themselves, the prefix and postfix operators do the same thing.  The variable being incremented gets updated at different times if these operators are embedded in a bigger expression prefix : increment/decrement performed first postfix : increment/decrement done last

4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Increment and Decrement  If count currently contains 45, then the statement total = count++; assigns 45 to total and 46 to count  If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  Another common operation consists of performing an operation on that variable and storing the result back in the same variable  Java provides assignment operators to simplify this process  For example, the statement num = num + count; can be replaced by num += count;

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  Java also provides assignment operators for all the binary operations. x += a;add a to x and store the new value x -= a;subtract a from x and store the new value x *= a;multiply x by a and store the new value x /= a;divide x by a and store the new value i %= j;replace i by i % j

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  The right hand side of an assignment operator can be a complex expression  Semantics of assignment operators: The entire right-hand expression is evaluated Then the result is combined with the original variable  For example result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);

8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Assignment Operators  The behavior of some assignment operators depends on the types of the operands  If the operands to the += operator are strings, the assignment operator performs string concatenation  The behavior of an assignment operator ( += ) is always consistent with the behavior of the "regular" operator ( + )  The /= operator does integer or floating point division depending on its operands.

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Repetition  Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met.  Java has three repetition statements: while do-while for

10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The while Statement  In Java, while statements follow a general format: while ( )  For example: int sum = 0, number = 1; while (number <= 100){ sum = sum + number; number = number + 1; }

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The while Statement  Repetition statements are also called loop statements, and the is known as the loop body.

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Semantics of a while Statement  The is evaluated.  If the is true, the is executed.  This sequence is repeated as long as the is true.

13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow chart for while

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Loop Patterns  In a count-controlled loop, the loop body is executed a fixed number of times. int counter = 0; while (counter < 100) doSomething();  In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered. int value = kbd.nextInt(); while (value != SENTINEL) value = kbd.nextInt();

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Repetition Pitfalls  There are several different types of potential programming problems we should keep in mind as we develop our programs. When writing repetition statements, it is important to ensure that the loop will eventually terminate. It is important that the boolean expression be correct.

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Infinite loops * An infinite loop will never stop int product = 0; while (product < 5000) { product = product * 5; }  Because product is initialized to 0, product will never be larger than 5000 (0 = 0 * 5), so the loop will never terminate.

17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Another Infinite Loop  In this example, (the while statement of which is also an infinite loop), count will equal 9 and 11, but not 10. int count = 1; while (count != 10) { count = count + 2; }  This is a case of not thinking about the termination condition carefully enough.

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. More Pitfalls  The off-by-one error is another frequently-encountered pitfall. Check the initial value of your loop variable carefully Check the condition you use for terminating the loop

19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Use real numbers properly  Real numbers should not be used in testing or increment, because only an approximation of real numbers can be stored in a computer. double x = 0.0; while (x<=1.0) x = x +.1;  Real numbers should not be tested for equality Math.abs(x - 1.0) <.01

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The do-while Statement  The while statement is a pretest loop, because the test is done before the execution of the loop body. Therefore, the loop body may not be executed.  The do-while statement is a posttest loop. With a posttest loop statement, the loop body is executed at least once.

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Syntax of do-while  The format of the do-while statement is: do while ( );  The is executed until the becomes false.

22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example of do-while Statement int sum = 0, number = 1; do { sum += number; number++; } while (sum <=1000000);

23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for do-while

24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Loop-and-a-Half Repetition Control  Loop-and-a-half repetition control can be used to test a loop's terminating condition in the middle of the loop body. Example: when reading data until some sentinel value is entered, you don't generally want to process the sentinel.  It is implemented by using reserved words while, if, and break.

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Loop-and-a-Half Example 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."); }

26 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Alternate Loop-and-a-Half for Input String name = kbd.next(); while (name.length() == 0){ System.out.println("Invalid Entry. " + "You must enter at least one character."); name = kbd.next(); }

27 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for loop-and-a-half

28 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pitfalls  Be aware of two concerns when using the loop-and-a-half control: The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop. Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks ). It is good practice to enforce the one-entry one-exit control flow.

29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Confirmation Dialog  JOptionPane has another form of dialog that we haven't seen before  A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, "Play Another Game?", /*prompt*/ "Confirmation", /*dialog title*/ JOptionPane.YES_NO_OPTION /*button options*/);

30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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); }

31 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The for Statement  The for statement is good for counting loops.  The syntax of the for statement is as follows: for ( ; ; ) int i, sum = 0; for (i = 1,i <=100, i++){ sum += i; }

32 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Flow Chart for for Statement

33 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The for Statement  The variable i in the example statement is called a control variable. It keeps track of the number of repetitions.  The can be by any amount, positive or negative.  for statements are often used for counting loops.

34 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Ch6DroppingWaterMelon.java  We want to to calculate the position of an object dropped from height H at t=0 as a function of time P = H - 16 t 2  Use a loop and test for H<=0

35 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Nested loops  A loop statement can be nested inside another loop statement.  The inner loop repeats the appropriate number of times for each execution of the outer loop.  For example, in for (int i=0; i<10; i++) for (int j=0; j<5; j++) sum += i + j; the body of the loop executes 10 * 5 = 50 times.

36 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example:  The price table for carpets ranging in size from 11 x 5 to 20 x 25 ft. whose unit price is $19 per sq. ft.  The outer for statement ranges from the first row (width = 11) to the last row (width = 20).  For each repetition of the outer for, the inner for statement is executed, which ranges from the first column (length = 5) to the fifth (length = 25).

37 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Nested loops  A loop statement can be nested inside another loop statement. int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19/sq. ft. System.out.print (" " + price); } //finished one row; move on to next row System.out.println(""); }


Download ppt "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement."

Similar presentations


Ads by Google