chapter 6 repetition. topics some additional operators –increment and decrement –assignment...

52
Chapter 6 Repetition

Post on 21-Dec-2015

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Chapter 6

Repetition

Page 2: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Topics

• Some additional operators– increment and decrement– assignment operators

• Repetition– while– do-while– for

• Random numbers

Page 3: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Increment and Decrement

• Updating a variable by adding or subtracting 1 is a very common operationi = i + 1;

j = j - 1;

• Java has operators that allow you to write this more compactlyi++ and ++i for incrementing

j-- and --j for decrementing

• Both operators can come either before (prefix) or after (postfix) the operand.

Page 4: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 5: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 6: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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;

Page 7: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 8: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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 exampleresult /= (total-MIN) % num;

is equivalent toresult = result / ((total-MIN) % num);

Page 9: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 10: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 11: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

The while Statement

• In Java, while statements follow a general format:

while ( <boolean expression> )<statement>

• For example:int sum = 0, number = 1;while (number <= 100){sum = sum + number;number = number + 1;

}

Page 12: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

The while Statement

• Repetition statements are also called loop statements, and the <statement> is known as the loop body.

• As long as the <boolean expression> is true, the loop body is executed.

Page 13: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Flow chart for while

Page 14: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 15: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 16: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 17: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 18: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 19: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 20: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 21: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Syntax of do-while

• The format of the do-while statement is:do

<statement>

while (<boolean expression>);

• The <statement> is executed until the <boolean expression> becomes false.

Page 22: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Example of do-while Statement

int sum = 0, number = 1;

do{

sum += number;

number++;

} while (sum <=1000000);

Page 23: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Flow Chart for do-while

Page 24: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 25: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.”);

}

Page 26: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Flow Chart for loop-and-a-half

Page 27: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 28: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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);

Page 29: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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); }

Page 30: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

The for Statement

• The format of the for statement is as follows:for (<initialization>; <boolean expression>;

<increment>)

<statement>

int i, sum = 0;

for (i = 1,i <=100, i++){

sum += i; //equivalent to sum = sum + 1;

}

Page 31: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Flow Chart for for Statement

Page 32: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

The for Statement

• The variable i in the example statement is called a control variable. It keeps track of the number of repetitions.

• The <increment> can be by any amount, positive or negative.

• for statements are often used for counting loops.

Page 33: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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 t2 + H

• Use a loop

Page 34: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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(“”);

}

Page 35: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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).

Page 36: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 37: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 38: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 39: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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"

Page 40: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 41: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

Loan Tables

• The start method can be expressed astell 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?”;

Page 42: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 43: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 44: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 45: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 46: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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);

Page 47: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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.

Page 48: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 49: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 50: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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

Page 51: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

51

Recursive Definitions

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

2

6

24

120

Page 52: Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers

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