Download presentation
Presentation is loading. Please wait.
1
Chapter 6 Repetition
2
Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers
3
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.
4
Increment and Decrement In a statement by themselves, the prefix and postfix operators do the same thing. These operators can be embedded in an expression. The variable being incremented gets updated at different times for the two cases –prefix : increment/decrement performed first –postfix : increment/decrement done last
5
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
6
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;
7
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
8
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);
9
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.
10
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
11
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; }
12
The while Statement Repetition statements are also called loop statements, and the is known as the loop body. As long as the is true, the loop body is executed.
13
Flow chart for while
14
Loop Patterns In a count-controlled loop, the loop body is executed a fixed number of times. In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered.
15
Repetition Pitfalls When writing repetition statements, it is important to ensure that the loop will eventually terminate. There are several different types of potential programming problems we should keep in mind as we develop our programs.
16
Infinite loop 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
Overflow error int count = 1; while (count != 10) { count = count + 2; } In this example, (the while statement of which is also an infinite loop), count will equal 9 and 11, but not 10.
18
Numeric 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. 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.
19
More Pitfalls Real numbers should not be used in testing or increment, because only an approximation of real numbers can be stored in a computer. The off-by-one error is another frequently- encountered pitfall.
20
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
Syntax of do-while The format of the do-while statement is: do while ( ); The is executed until the becomes false.
22
Example of do-while Statement int sum = 0, number = 1; do{ sum += number; number++; } while (sum <=1000000);
23
Flow Chart for do-while
24
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
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
Flow Chart for loop-and-a-half
27
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 (break s). It is good practice to enforce the one-entry one-exit control flow.
28
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, /*prompt*/ “Play Another Game?”, /*dialog title*/ “Confirmation”, /*button options*/ JOptionPane.YES_NO_OPTION);
29
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); }
30
The for Statement The format of the for statement is as follows: for ( ; ; ) int i, sum = 0; for (i = 1,i <=100, i++){ sum += i; //equivalent to sum = sum + 1; }
31
Flow Chart for for Statement
32
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.
33
Ch6DroppingWaterMelon.java Want to to calculate the position of an object dropped from height H at time t=0 as a function of time P = -16 t 2 + H Use a loop
34
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 per sq. ft. System.out.print (“ “+ price); } //finished one row; move on to next row System.out.println(“”); }
35
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).
36
Formatting Output To align values with varying numbers of digits, we must vary the number of spaces in front of the values. The idea behind formatted output is to allocate the same amount of space for the output values and align the values within the allocated space. We call the space occupied by an output value the field. The number of characters allocated to a field is the field width.
37
Aligning Columns of Numbers How to place a varying number of spaces to align the output values. –Hyphen is used here to indicate the blank space. Need to determine how many spaces each number takes up and then pad with spaces to make it the the desired width.
38
Class for Formatting Output We will define a noninstantiable helper class called Ch6Format. The pad method has an integer argument and returns a String object with the specified number of blank spaces.
39
Overloaded pad Method There are two versions of the pad method. –The first returns the specified number of blank spaces. Ch6Format.pad(6) --> "------" –The second returns the specified number of designated symbols. Ch6Format.pad(2, "one") --> "oneone" Ch6Format.pad(3, "xy") --> "xyxyxy"
40
Example: Loan Tables The goal of this exercise is to design a program that generates a loan table. The table will compare different monthly payments for a set loan amount, with varying loan periods in each column and different interest rates in each row.
41
Loan Tables The start method can be expressed as tell the user what the program does; prompt the user “Do you want to generate a loan table?”; while (the user says YES) input the loan amount; generate the loan table; prompt the user “Do another loan table?”;
42
Pseudocode The start method was expressed in pseudocode. Pseudocode is an informal language used to express an algorithm. It is useful in clarifying the purpose or function of the program without being tied down to the syntactic rules of a particular programming language. Also useful for describing algorithms that may be implemented in many different languages.
43
Loan Tables Other methods in the program: –describeProgram: tells the user what the program does if the user requests it. –getLoanAmount: gets the loan amount from the user. –generateLoanTable: generates the loan table. To compute the monthly loan payment, reuse the Loan class defined in Chapter 4.
44
Random Number Generation The method Math.random is called a pseudorandom number generator and returns a number of type double that is greater than or equal to 0.0 but less than 1.0. The generated number is called a pseudorandom number because it is not truly random.
45
Random Integers The number returned from the random method ranges from 0.0 up to (but not including) 1.0. If we want to generate random integers, we must perform a conversion so the number will fall within the desired range. Use the formula: Y = {X × (max – min + 1)} + min where X is the number returned by random.
46
Random Integers The formula expressed in Java: //assume correct values are assigned to //‘max’ and ‘min’ int randomNumber = (int) (Math.floor(Math.random * max-min+1)) + min);
47
Random Number Example Ch6TestRandomGenerator generates N random numbers between 1 and 4 to simulate the suit of a drawn card. It keeps one counter for each suit, and increments the matching counter after a random number is generated. At the end of the generation, it prints the ratio count/N.
48
Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers of various types –float nextFloat() –int nextInt() –int nextInt(n) produces integer in range 0 to n-1
49
49 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition is one which uses the word or concept being defined in the definition itself; when defining an English word, a recursive definition usually is not helpful
50
50 Recursive Definitions Mathematical formulas often are expressed recursively N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive This definition can be expressed recursively as: 1! = 1 N! = N * (N-1) The concept of the factorial is defined in terms of another factorial until the base case of 1! is reached
51
51 Recursive Definitions 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 2 6 24 120
52
52 Infinite Recursion All recursive definitions must have a non- recursive part –If they don't, there is no way to terminate the recursive path –A definition without a non-recursive part causes infinite recursion This problem is similar to an infinite loop with the definition itself causing the infinite "loop" The non-recursive part often is called the base case
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.