java programming: from the ground up chapter 5 repetition

74
Java Programming: From the Ground Up Chapter 5 Repetition

Upload: melinda-cannon

Post on 30-Dec-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Programming: From the Ground Up Chapter 5 Repetition

Java Programming:From the Ground Up

Chapter 5Repetition

Page 2: Java Programming: From the Ground Up Chapter 5 Repetition

Repetition

Three Java constructions allow repetition in programs:

• the while statement

• the do-while statement

• the for statement. 

Page 3: Java Programming: From the Ground Up Chapter 5 Repetition

The while Statement

We can write a program that adds exactly 5 integers and a different application that sums exactly 50 integers. But, can we write a program flexible enough to add 5 integers, 50 integers, 50,000 integers or even 50,000,000 integers?

Page 4: Java Programming: From the Ground Up Chapter 5 Repetition

The while Statement

The following segment performs addition of 50 numbers with just a few lines of code. There is nothing special about 50 and we can just as easily add 500,000 numbers:

1. int sum = 0;2. int count = 0;3. while(count < 50) 4. {5. sum = sum + input.nextInt();6. count++;7. }8. System.out.print(“Sum is “ + sum);

Page 5: Java Programming: From the Ground Up Chapter 5 Repetition

The while Statement

The statements on lines 3– 8, execute as follows: 

The condition on line 3 (count < 50) is evaluated.If the condition, count < 50, is true,

• Line 5 sum = sum + input.nextInt() : A number is accepted from the keyboard and added to sum.

• Line 6 count++ : Variable count is increased by 1 .• Program control returns to the “top of the loop” (line 3) and the process

repeats.

If the condition on line 3 is false,

• The statements on lines 5 and 6 are skipped.• Program control passes to line 8 and the sum is displayed.

 

Page 6: Java Programming: From the Ground Up Chapter 5 Repetition

The while Statement

The assignment statement:

sum = sum + input.nextInt() // line 5

executes 50 times.

Page 7: Java Programming: From the Ground Up Chapter 5 Repetition

Adding 50 integers

Page 8: Java Programming: From the Ground Up Chapter 5 Repetition

The while statement

Problem Statemen

• Write a program that sums of a list of integers supplied by a user.

• The list can be of any size.

• The program should prompt the user for the number of data.  

Page 9: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

The following application utilizes three variables: size, sum, and count.

• size is the number of data;

• sum holds a running sum of the numbers supplied by the user so that each time the user enters a number, that number is added to sum, and

• count keeps track of the number of data

Page 10: Java Programming: From the Ground Up Chapter 5 Repetition

1. import java.util.*;2. public class AddEmUp3. {4. // adds an arbitrarily long list of integers5. // the user first supplies the size of the list6. public static void main (String[] args)7. {8. Scanner input =new Scanner(System.in);9. int sum = 0; // Running sum10. int count = 0; //Keeps track of the number of integers 11. int size ; / Size of the list12. System.out.print("How many numbers would you like to add? ");13. size = input.nextInt();14. System.out.println("Enter the "+size+" numbers");

15. while (count < size) // while number of data < size repeat:16. {17. sum = sum + input.nextInt(); // read next integer, add to sum18. count++; // keep track of the number of data, so far 19. }20. System.out.println(“Sum: “+ sum);21. }

Page 11: Java Programming: From the Ground Up Chapter 5 Repetition

Output

How many numbers would you like to add? 3Enter the 3 numbers579Sum: 21

----------------------------------------------------------------How many numbers would you like to add? 12Enter the 12 numbers23 45 65 23 43 12 87 56 34 31 84 90Sum: 593

Page 12: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

9. int sum = 0; 10. int count = 0;11. int size ; 12. System.out.print("How many numbers would you like to add? ");13. size = input.nextInt();

Page 13: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

15. while (count < size) // while number of data < size repeat:16. {17. sum = sum + input.nextInt(); // read next integer, add to sum18. count++; // keep track of the number of data, so far 19. }

Page 14: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

15. while (count < size) // while number of data < size repeat:16. {17. sum = sum + input.nextInt(); // read next integer, add to sum18. count++; // keep track of the number of data, so far 19. }

Page 15: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

15. while (count < size) // while number of data < size repeat:16. {17. sum = sum + input.nextInt(); // read next integer, add to sum18. count++; // keep track of the number of data, so far 19. }

Page 16: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

15. while (count < size) // while number of data < size repeat:16. {17. sum = sum + input.nextInt(); // read next integer, add to sum18. count++; // keep track of the number of data, so far 19. }20. System.out.println(“Sum: “+ sum);

Page 17: Java Programming: From the Ground Up Chapter 5 Repetition

The actions of a while loop

Page 18: Java Programming: From the Ground Up Chapter 5 Repetition

The flag

• Another mechanism used to terminate a loop is a flag or sentinel.

 • A flag or sentinel is a value appended to a data collection

that signals the end of the data.  • A sentinel cannot be a number that is a feasible data value.

For example, if all data are positive integers, you might use -1 as a flag and a list of data might have the form 234, 564, 567, 128, 123, -1.

Page 19: Java Programming: From the Ground Up Chapter 5 Repetition

The flag

Problem Statement

Write a program that computes the sum a list of integers that is supplied by a user.

The end of data is signaled by the value -999.

This value is used only as a flag and is not included in the sum. 

Page 20: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

 

1. import java.util.*;2. public class AddEmUpAgain3. {4. // adds an arbitrarily long list of integers5. // -999 signals the end of data6. public static void main (String[] args)7. {8. Scanner input =new Scanner(System.in);9. final int FLAG = -999; // signals the end of data10. int sum = 0; // Running sum11. int number; // holds the next integer to be added12. System.out.println("Enter the numbers. End with "+FLAG);

13. number = input.nextInt();14. while (number != FLAG) // FLAG signals the end of data15. { 16. sum += number; // add the current integer to sum17. number = input.nextInt(); // read the next integer18. }19. System.out.println("Sum: "+ sum);20. }21. }

Page 21: Java Programming: From the Ground Up Chapter 5 Repetition

Output

Enter the numbers. End with -9995 6 7 -999Sum: 18

Page 22: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

9. final int FLAG = -999; 10. int sum = 0; 11. int number; 12. System.out.println("Enter the numbers. End with "+FLAG);

13. number = input.nextInt();14. while (number != FLAG) 15. { 16. sum += number; 17. number = input.nextInt();18. }

The constant FLAG (line 9) serves as a sentinel that signals the end of data.

Page 23: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

9. final int FLAG = -999; 10. int sum = 0; 11. int number; 12. System.out.println("Enter the numbers. End with "+FLAG);

13. number = input.nextInt();14. while (number != FLAG) 15. { 16. sum += number; 17. number = input.nextInt();18. }

The first datum is read outside the while loop (line 13). If the statement on line 13 is omitted, the compiler generates anerror message on line 14:

variable number might not have been initialized.

If the first datum happens to be FLAG, the program neverenters the loop and correctly determines that the sum is 0.

Page 24: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

9. final int FLAG = -999; 10. int sum = 0; 11. int number; 12. System.out.println("Enter the numbers. End with "+FLAG);

13. number = input.nextInt();14. while (number != FLAG) 15. { 16. sum += number; 17. number = input.nextInt();18. }

The last action of the loop is an input statement. Consequently, when the user enters -999, the sentinel value isread but not included in the sum.

 

Page 25: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

A more general program might prompt the user for the sentinel value rather than forcing the use of –999. This improvement is easily accomplished by replacing:

  final int FLAG = -999;   with 

System.out.println(“Enter sentinel value: ”); final int FLAG = input.nextInt();

Page 26: Java Programming: From the Ground Up Chapter 5 Repetition

while Semantics

while(conition){

statement-1;statement -2; ….statement-n;

}

• condition, a boolean expression, is evaluated.• If condition evaluates to true,

– statement-1, statement-2, …, statement-n execute.– Program control returns to the top of the loop.– The process repeats (go to step 1).

• If condition evaluates to false, statement-1, statement-2,…, statement-n are skippedProgram control passes to the first statement after the loop.

Page 27: Java Programming: From the Ground Up Chapter 5 Repetition

while Semantics

The semantics of the while statement

Page 28: Java Programming: From the Ground Up Chapter 5 Repetition

Loops: A Source of Power; A Source of Bugs

Two common bugs:

• The infinite loop.

• The “off by one” error.

Page 29: Java Programming: From the Ground Up Chapter 5 Repetition

The Infinite Loop

• An infinite loop continues forever. • An infinite while loop exists if the loop’s terminating condition

fails to evaluate to false:

while (count < size) { sum = sum + input.nextInt(); } 

• The problem is a failure to increment count.  

Page 30: Java Programming: From the Ground Up Chapter 5 Repetition

A loop may never execute

• A loop may never execute:  count = 0; while (count > size) { number = input.nextInt(); sum += number; count++; } • Since count is initialized to 0, and the user presumably

enters a positive integer for size, then the expression count > size evaluates to false, and the statements of the loop never execute.

Page 31: Java Programming: From the Ground Up Chapter 5 Repetition

The “Off by One” Error

This error occurs if a loop executes one too many or one too few times.

Page 32: Java Programming: From the Ground Up Chapter 5 Repetition

The “Off by One” Error

The following erroneous program is intended to calculate thesum of the first n positive integers: 1+2+3+ …+ n. The usersupplies a value for n:

Page 33: Java Programming: From the Ground Up Chapter 5 Repetition

The “Off by One” Error

1. import java.util.*;2. public class AddUpToN // with an error!3. {4. public static void main (String[] args)5. {6. Scanner input =new Scanner(System.in);7. int sum = 0; // Cumulative sum8. int number; // find sum 1+2+...+ number9. int count = 1; //counts 1 to number10. System.out.print("Enter a positive integer: ");11. number = input.nextInt(); // read the next integer12. while (count < number) //here's the bug13. {14. sum += count;15. count++;16. }17. System.out.println("The sum of the first "+number+

" positive integers is "+ sum);18. }19. }

 

Page 34: Java Programming: From the Ground Up Chapter 5 Repetition

(Erroneous) output

Enter a positive integer: 5The sum of the first 5 positive integers is 10 The loop executes four rather than five times. The error lies inthe condition, which should be count <= number rather thancount < number.

Page 35: Java Programming: From the Ground Up Chapter 5 Repetition

The “Off by One” Error

• The following program is supposed to calculate the average of a list of numbers terminated by the sentinel value -999.

• The program does not work correctly. It mistakenly includes the sentinel as part of the data:

Page 36: Java Programming: From the Ground Up Chapter 5 Repetition

The “Off by One” Error

public class Average // PRODUCES FAULTY OUTPUT!{ public static void main (String[] args) { Scanner input =new Scanner(System.in); final int FLAG = -999; double sum = 0; // running sum double number; // holds the next integer to be added int count = 0; // counts the number of data double average; System.out.println("Enter the numbers end with "+FLAG); number = input.nextDouble(); // read the next number while (number != FLAG) { count++; number = input.nextDouble(); // read the next number sum += number; // add the current integer to sum } average = sum/count; System.out.println("Average: "+ average); }}

Page 37: Java Programming: From the Ground Up Chapter 5 Repetition

(Erroneous) output

Enter the numbers end with -999123-999Average: -331.3333333333333

Page 38: Java Programming: From the Ground Up Chapter 5 Repetition

The sentinel value (-999) is included in the sum and the first number (1) is not, i.e., sum is computed with the values 2, 3, and -999.

 Reversing the last two lines of the loop corrects the problem:

while (number != FLAG){

count++;sum += number; number = input.nextDouble

}

Page 39: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

A do-while loop checks the condition at the end of the loop body

 

Page 40: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

1. int x; // must be positive 2. do 3. { 4. System.out.println("Enter a number > 0"); 5. x = input.nextInt(); // input is a Scanner 6. } while (x <= 0); // if negative, repeat

• The statement on line 4 prompts the user for a positive number.

• The statement on line 5 reads a value and assigns that value to variable x.

• The condition (x <= 0) on line 6 is evaluated.

• If the condition is true the loop repeats the actions of lines 4 and 5; if the condition is false the loop terminates.

Page 41: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

• The body of the loop (lines 4 and 5) executes once before the condition is tested.

• A do-while loop is guaranteed to execute at least once

Page 42: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

Problem Statement

Write a program that calculates the sum of a list of integers thatis interactively supplied by a user.

The program should prompt the user for the number ofdata.

The program should ensure that each number supplied by theuser is positive.

Page 43: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

1. import java.util.*;2. public class DoWhileAdd3. {4. public static void main (String[] args)5. {6. Scanner input =new Scanner(System.in);7. int size; // the number of integers in the sum8.

Page 44: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

7. do // repeat until size is positive8. {10. System.out.print("How many numbers would you like to add? ");11. size = input.nextInt();12. } while (size <= 0);

13. System.out.println("Enter the "+size+" numbers");14. int sum = 0; // the running sum15. int count = 0; // keeps track of the number of data16. while (count <size)17. {18. sum = sum + input.nextInt(); // read the next integer, add to sum19. count++; // increment counter 20. }21. System.out.println("Sum: "+ sum);22. }23. }

Page 45: Java Programming: From the Ground Up Chapter 5 Repetition

Output

How many numbers would you like to add? 0How many numbers would you like to add? -3How many numbers would you like to add? 3Enter the 3 numbers579Sum: 21

Page 46: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

7. do // repeat until size is positive8. {10. System.out.print("How many numbers would you like to add? ");11. size = input.nextInt();12. } while (size <= 0);

The condition on line 12 (size<= 0) is evaluated after the block executes.

If the condition evaluates to true, control passes back to line 10 and the loop executes again

If the condition is false, the loop terminates.

Page 47: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

The syntax of the do-while statement is: do {

statement-1; statement-2; …; statement-n; } while (condition);

Page 48: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

Execution of the do-while statement proceeds as follows:

• statement-1, statement-2,..., statement-n execute.

• condition is evaluated.

• If the condition is true, the process repeats (go back to statement-1).

• If condition is false, the loop terminates and program control passes to the first statement following the loop.

Page 49: Java Programming: From the Ground Up Chapter 5 Repetition

The do-while Statement

The semantics of the do-while statement

Page 50: Java Programming: From the Ground Up Chapter 5 Repetition

Which Loop?

• The while loop is top-tested, i.e., the condition is evaluated before any of the loop statements executes. If the condition of a while loop is initially false the loop never executes.

• The do-while loop, on the other hand, is bottom-tested, i.e., the condition is tested after the first iteration of the loop.

• A do-while loop always executes at least once.

Page 51: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

Use a for statement when you can count the number of times that a loop executes.

Page 52: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

The following program segment uses a for loop to print the verse of a familiar, if boring, song exactly three times:

for (int i = 1; i <=3; i++){

System.out.println(“Row, row, row your boat, gently down the stream,”); System.out.println(“Merrily, merrily, merrily, merrily; life is but a dream”);

System.out.println();}

Page 53: Java Programming: From the Ground Up Chapter 5 Repetition

1. for (int i = 1; i <= 3; i++)2. {3 - 5 …….6. }

The loop executes as follows:

1.The variable i is declared and initialized to 1 (int i = 1); i keeps track of the number of iterations; i counts.

2. The condition, i<= 3, on line 1 is evaluated.

3. If the condition, i <= 3, is true: – Lines 3, 4, and 5 execute– The statement, i++, on line 1 executes.– Go to step 2 (check whether or not i <= 3).

4. If the condition, i <= 3, is false the loop terminates.

Page 54: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

A for loop that displays the verse of a song three times

Page 55: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

Problem Statement

Using a for statement, write a program that sums a list ofintegers.

The program should prompt the user for the size of the list. 

Page 56: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

1. import java.util.*;2. public class ForAddEmUp3. {4. public static void main (String[] args)5. {6. Scanner input =new Scanner(System.in); 7. int sum = 0; // Cumulative sum8. int size; // Number of integers to add9. int number; // holds the next integer to beadded 10. System.out.print("How many numbers to add? ");11. size = input.nextInt();12. System.out.println("Enter the "+size+" numbers"); 13. for (int count = 1; count <= size; count++) 14. {15. number = input.nextInt(); // read the next integer16. sum += number; // add number to sum17. } 18. System.out.println("Sum: "+ sum);19. }20. }

Page 57: Java Programming: From the Ground Up Chapter 5 Repetition

Output

How many numbers would you like to add? 4Enter the 4 numbers3579Sum: 24

Page 58: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

The “header” of the for statement,

for (int count = 1; count <= size; count++)

consists of three parts:

• the initialization statement: int count = 1, • the loop condition (a boolean expression): count <=

size• the update statement: count++.

Page 59: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

The for statement proceeds as follows: 

The initialization statement (count = 1) executes. The variable count is both declared and initialized to 1. The variable count is called the control variable. Because count is declared within the for statement, count is accessible only within the loop.

Page 60: Java Programming: From the Ground Up Chapter 5 Repetition

Discussion

• The loop condition, count <= size, is tested.

• If the loop condition is true, then: The block (lines 14-17) executes. The update statement executes (count++, line 13). The process repeats from step 2 (Is the loop condition still

true?).

• If the loop condition is false, then: The loop terminates. Program control passes to the first statement after the loop

(line 18).

Page 61: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

The syntax of the for statement is: for (initialization; loop condition; update statement(s)) {

statement-1: statement-2; … statement-n:

}   The braces may be omitted if the statement block consists of a

single statement. 

Page 62: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

The semantics of the for statement are:

The initialization statement executes.

The loop condition (a boolean expression) is evaluated.

If the loop condition is true, then:• statement-1, statement-2,…, statement-n execute,• The update-statement(s) executes, • Go to step 2.

If the loop condition is false, then program control passes to the first statement following the block consisting of statement-1, statement-2,…, statement-n.

Page 63: Java Programming: From the Ground Up Chapter 5 Repetition

The for Statement

• The initialization is performed exactly once.

• The loop condition is always tested before the statement block executes.

• The update statement always executes after the actions of the statement block.

• The declared, initialized variables disappear after the for loop completes execution.

The semantics of the for statement

Page 64: Java Programming: From the Ground Up Chapter 5 Repetition

Example

• When you supply your credit card number to an online vendor, data input errors are checked before your credit card is validated. For example, credit cards issued by Visa all have numbers beginning with the digit 4 and those issued by American Express begin with 34 or 37.

 • Another method of validation is the Luhn algorithm. The Luhn algorithm

detects some, but not all, invalid numbers. Thus, this algorithm can alert a vendor to some bad numbers but it cannot guarantee that a credit card number is valid.

 

Page 65: Java Programming: From the Ground Up Chapter 5 Repetition

Example

The method works as follows: • Beginning with the second rightmost digit and moving

right to left, double every other digit. If the doubling process produces a value greater than 9, subtract 9 from that value.

• Form a sum of all the products ("new" digits) and the unchanged digits.

• If the sum does not end in 0 the card is invalid.

Page 66: Java Programming: From the Ground Up Chapter 5 Repetition

Example

• For example, to check the validity of credit card number 5113 4765 1234 8002 proceed as follows:

1. Double alternate digits. Subtract 9 from products exceeding 9:

Double alternate digits; subtract 9 if the result is greater than 9

2. Form the sum: 1+1+2+3+8+7+3+5+2+2+6+4+7+0+0+2 = 53.

3. The sum 53 does not end in zero so the card number is invalid.

Page 67: Java Programming: From the Ground Up Chapter 5 Repetition

Example

Problem Statement

Write a program that determines whether a credit card number with 16 (or fewer) digits passes the Luhn test.

 

Page 68: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

• The solution assumes that the maximum number of digits is 16.

 • An implementation of the Luhn algorithm requires that we

extract the digits of a card number, digit by digit, right to left. To extract the digits and move right to left through a number, the solution utilizes the % operator and integer division. Using the % operator, we can easily extract the rightmost digit from a number: 12345 % 10 = 5.

 • With integer division, we can remove the rightmost digit from

a number to obtain a “new” number without the rightmost digit: 12345/10 = 1234.

Page 69: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

1. import java.util.*;2. public class CheckCreditCard3. {4. public static void main (String[] args)5. {6. Scanner input =new Scanner(System.in);7. final int MAX_DIGITS = 16;

// maximum number of digits for a credit card8. long number; // credit card number9. long sum = 0; // the final value of sum must end in zero10. long digit;11.  12. System.out.print("Enter Credit Card Number:" );13. number = input.nextLong(); 

Page 70: Java Programming: From the Ground Up Chapter 5 Repetition

Solution

14. for (int i = 1; i <= MAX_DIGITS; i++) // for each digit, i counts digits15. {16. digit = number % 10; // extract the rightmost digit17. if (i % 2 == 0) //double every other digit18. {19. digit = digit*2;20. if (digit > 9) // subtract 9 if the product is larger than 921. digit -= 9;22. }23. sum += digit; // add the digit to the running sum24. number =number/10; // remove the rightmost digit25. }26. if (sum % 10 != 0) // check the rightmost digit of sum27. System.out.println("Invalid number");28. else29. System.out.println("Credit card number passes test");30. }31. }

Page 71: Java Programming: From the Ground Up Chapter 5 Repetition

Output

Output 1:Enter Credit Card Number: 5113476512348002Invalid number Output 2:Enter Credit Card Number: 123456789876543Credit card number passes test

Page 72: Java Programming: From the Ground Up Chapter 5 Repetition

Nested Loops

• Loops may be nested within loops: 

 

• The inner “j-loop” (lines 3 through 6) is nested within the outer “i-loop” (lines 1 through 8). For each value of i (1, 2, 3, and 4), the j-loop executes once. The println statement on line 5 executes 4×3 = 12 times. The empty println statement (line 7) is not part of the inner loop, so this statement, which prints a blank line, executes just 4 times, once for each value of i.

Nested loops

Page 73: Java Programming: From the Ground Up Chapter 5 Repetition

Nested Loops

Tracing a nested loop

Page 74: Java Programming: From the Ground Up Chapter 5 Repetition

The break Statement Revisited

• When a break statement executes within a switch statement, the switch statement terminates and program control passes to the first statement following the switch statement. Similarly, a break statement can be used to terminate, or “break out of” a loop.

 • When a break statement executes within a loop, the loop

terminates and program control passes to the first statement following the loop.