Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming: From the Ground Up

Similar presentations


Presentation on theme: "Java Programming: From the Ground Up"— Presentation transcript:

1 Java Programming: From the Ground Up
Chapter 5 Repetition

2 Repetition Three Java constructions allow repetition in programs:
the while statement the do-while statement the for statement.

3 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?

4 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: int sum = 0; int count = 0; while(count < 50) { sum = sum + input.nextInt(); count++; } System.out.print(“Sum is “ + sum);

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

6 The while Statement The assignment statement:
sum = sum + input.nextInt() // line 5 executes 50 times.

7 Adding 50 integers

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

9 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

10 import java.util.*; public class AddEmUp { // adds an arbitrarily long list of integers // the user first supplies the size of the list public static void main (String[] args) Scanner input =new Scanner(System.in); int sum = 0; // Running sum int count = 0; //Keeps track of the number of integers int size ; / Size of the list System.out.print("How many numbers would you like to add? "); size = input.nextInt(); System.out.println("Enter the "+size+" numbers"); while (count < size) // while number of data < size repeat: sum = sum + input.nextInt(); // read next integer, add to sum count++; // keep track of the number of data, so far } System.out.println(“Sum: “+ sum);

11 Output How many numbers would you like to add? 3 Enter the 3 numbers 5
7 9 Sum: How many numbers would you like to add? 12 Enter the 12 numbers Sum: 593

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

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

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

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

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

17 The actions of a while loop

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

19 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 This value is used only as a flag and is not included in the sum.

20 Solution import java.util.*; public class AddEmUpAgain {
import java.util.*; public class AddEmUpAgain { // adds an arbitrarily long list of integers // -999 signals the end of data public static void main (String[] args) Scanner input =new Scanner(System.in); final int FLAG = -999; // signals the end of data int sum = 0; // Running sum int number; // holds the next integer to be added System.out.println("Enter the numbers. End with "+FLAG); number = input.nextInt(); while (number != FLAG) // FLAG signals the end of data sum += number; // add the current integer to sum number = input.nextInt(); // read the next integer } System.out.println("Sum: "+ sum);

21 Output Enter the numbers. End with -999 Sum: 18

22 Discussion final int FLAG = -999; int sum = 0; int number; System.out.println("Enter the numbers. End with "+FLAG); number = input.nextInt(); while (number != FLAG) { sum += number; } The constant FLAG (line 9) serves as a sentinel that signals the end of data.

23 Discussion The first datum is read outside the while loop (line 13).
final int FLAG = -999; int sum = 0; int number; System.out.println("Enter the numbers. End with "+FLAG); number = input.nextInt(); while (number != FLAG) { sum += number; } The first datum is read outside the while loop (line 13). If the statement on line 13 is omitted, the compiler generates an error message on line 14: variable number might not have been initialized. If the first datum happens to be FLAG, the program never enters the loop and correctly determines that the sum is 0.

24 Discussion The last action of the loop is an input statement.
final int FLAG = -999; int sum = 0; int number; System.out.println("Enter the numbers. End with "+FLAG); number = input.nextInt(); while (number != FLAG) { sum += number; } The last action of the loop is an input statement. Consequently, when the user enters -999, the sentinel value is read but not included in the sum.

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

26 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 skipped Program control passes to the first statement after the loop.

27 The semantics of the while statement
while Semantics The semantics of the while statement

28 Loops: A Source of Power; A Source of Bugs
Two common bugs: The infinite loop. The “off by one” error.

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

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

31 The “Off by One” Error This error occurs if a loop executes one too many or one too few times.

32 The “Off by One” Error The following erroneous program is intended to calculate the sum of the first n positive integers: …+ n. The user supplies a value for n:

33 The “Off by One” Error import java.util.*;
public class AddUpToN // with an error! { public static void main (String[] args) Scanner input =new Scanner(System.in); int sum = 0; // Cumulative sum int number; // find sum number int count = 1; //counts 1 to number System.out.print("Enter a positive integer: "); number = input.nextInt(); // read the next integer while (count < number) //here's the bug sum += count; count++; } System.out.println("The sum of the first "+number " positive integers is "+ sum);

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

35 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:

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

37 (Erroneous) output Enter the numbers end with -999 1 2 3 -999 Average:

38 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 }

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

40 The do-while Statement
1. int x; // must be positive 2. do 3. { System.out.println("Enter a number > 0"); 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.

41 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

42 The do-while Statement
Problem Statement Write a program that calculates the sum of a list of integers that is interactively supplied by a user. The program should prompt the user for the number of data. The program should ensure that each number supplied by the user is positive.

43 Solution 1. import java.util.*; 2. public class DoWhileAdd 3. {
4. public static void main (String[] args) 5. { Scanner input =new Scanner(System.in); int size; // the number of integers in the sum

44 Solution do // repeat until size is positive {
System.out.print("How many numbers would you like to add? "); size = input.nextInt(); } while (size <= 0); System.out.println("Enter the "+size+" numbers"); int sum = 0; // the running sum int count = 0; // keeps track of the number of data while (count <size) { sum = sum + input.nextInt(); // read the next integer, add to sum count++; // increment counter } System.out.println("Sum: "+ sum); } 23. }

45 Output How many numbers would you like to add? 0
Enter the 3 numbers 5 7 9 Sum: 21

46 Discussion do // repeat until size is positive { System.out.print("How many numbers would you like to add? "); size = input.nextInt(); } 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.

47 The do-while Statement
The syntax of the do-while statement is: do { statement-1; statement-2; …; statement-n; } while (condition);

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

49 The do-while Statement
The semantics of the do-while statement

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

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

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

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

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

55 The for Statement Problem Statement
Using a for statement, write a program that sums a list of integers. The program should prompt the user for the size of the list.

56 Solution import java.util.*; public class ForAddEmUp {
public static void main (String[] args) Scanner input =new Scanner(System.in);  int sum = 0; // Cumulative sum int size; // Number of integers to add int number; // holds the next integer to beadded  System.out.print("How many numbers to add? "); size = input.nextInt(); System.out.println("Enter the "+size+" numbers");  for (int count = 1; count <= size; count++) number = input.nextInt(); // read the next integer sum += number; // add number to sum System.out.println("Sum: "+ sum); }

57 Output How many numbers would you like to add? 4 Enter the 4 numbers 3
5 7 9 Sum: 24

58 Discussion The “header” of the for statement, consists of three parts:
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++.

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

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

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

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

63 The semantics of 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

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

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

66 Double alternate digits; subtract 9 if the result is greater than 9
Example For example, to check the validity of credit card number 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: = 53. 3. The sum 53 does not end in zero so the card number is invalid.

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

68 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: % 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.

69 Solution import java.util.*; public class CheckCreditCard {
public static void main (String[] args) Scanner input =new Scanner(System.in); final int MAX_DIGITS = 16; // maximum number of digits for a credit card long number; // credit card number long sum = 0; // the final value of sum must end in zero long digit; System.out.print("Enter Credit Card Number:" ); number = input.nextLong();

70 Solution for (int i = 1; i <= MAX_DIGITS; i++) // for each digit, i counts digits { digit = number % 10; // extract the rightmost digit if (i % 2 == 0) //double every other digit digit = digit*2; if (digit > 9) // subtract 9 if the product is larger than 9 digit -= 9; } sum += digit; // add the digit to the running sum number =number/10; // remove the rightmost digit if (sum % 10 != 0) // check the rightmost digit of sum System.out.println("Invalid number"); else System.out.println("Credit card number passes test");

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

72 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

73 Nested Loops Tracing a nested loop

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


Download ppt "Java Programming: From the Ground Up"

Similar presentations


Ads by Google