1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops; Procedural Design reading: 5.1 – 5.2; 4.5.

Slides:



Advertisements
Similar presentations
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Advertisements

1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
Building Java Programs
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-3: Interactive Programs w/
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Topic 13 procedural design and Strings Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
1 Fencepost loops suggested reading: The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.
Building java programs, chapter 5 Program logic and indefinite loops.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
Copyright 2010 by Pearson Education Building Java Programs Scanner ; if / else; while loops ; random reading: 3.3 – 3.4, 4.1, 4.5, 5.1, 5.6.
CS 112 Introduction to Programming Loop Patterns: break; Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Building Java Programs Chapter 4 Lecture 4-1: Scanner ; cumulative algorithms reading: 3.3 – 3.4, 4.2.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Copyright 2010 by Pearson Education The if/else statement reading: 4.1, 4.6.
Building Java Programs
Categories of loops definite loop: Executes a known number of times.
CSc 110, Autumn 2017 Lecture 16: Fencepost Loops and Review
CSc 110, Autumn 2017 Lecture 17: while Loops and Sentinel Loops
Building Java Programs
Lecture 7: Input and Miscellaneous
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
CSc 110, Autumn 2016 Lecture 12: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
CSc 110, Spring 2017 Lecture 11: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
Building Java Programs Chapter 4
Building Java Programs
Fencepost loops reading: 4.1.
CSc 110, Spring 2018 Lecture 16: Fencepost Loops and while loops
Topic 14 while loops and loop patterns
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Loop problem Write a method printLetters that prints each letter from a word separated by commas. For example, the call: printLetters("Atmosphere") should.
Building Java Programs
CIS 110: Introduction to Computer Programming
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 – 3.4, 4.1, 4.5
CSE 142, Spring 2013 Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops; Procedural Design reading: 5.1 – 5.2; 4.5

2 A deceptive problem... Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas. For example, the call: printNumbers(5) should print: 1, 2, 3, 4, 5

3 Flawed solutions public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line of output } Output from printNumbers(5) : 1, 2, 3, 4, 5, public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line of output } Output from printNumbers(5) :, 1, 2, 3, 4, 5

4 Fence post analogy We print n numbers but need only n - 1 commas. Similar to building a fence with wires separated by posts: If we use a flawed algorithm that repeatedly places a post + wire, the last post will have an extra dangling wire. for (length of fence) { place a post. place some wire. }

5 Fencepost loop Add a statement outside the loop to place the initial "post." Also called a fencepost loop or a "loop-and-a-half" solution. place a post. for (length of fence - 1) { place some wire. place a post. }

6 Fencepost method solution public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line } Alternate solution: Either first or last "post" can be taken out: public static void printNumbers(int max) { for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); } System.out.println(max); // to end the line }

7 Fencepost question Write a method printPrimes that prints all prime numbers up to a given maximum in the following format. Example: printPrimes(50) prints [ ] If the maximum is less than 2, print no output. To help you, write a method countFactors which returns the number of factors of a given integer. countFactors(20) returns 6 due to factors 1, 2, 4, 5, 10, 20.

8 Fencepost answer // Prints all prime numbers up to the given max. public static void printPrimes(int max) { System.out.print("[2"); for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { System.out.print(" " + i); } System.out.println("]"); } // Returns how many factors the given number has. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of number } return count; }

9 while loops reading: 5.1

10 Categories of loops definite loop: Executes a known number of times. The for loops we have seen are definite loops. Print "hello" 10 times. Find all the prime numbers up to an integer n. Print each odd number between 5 and 127. indefinite loop: One where the number of times its body repeats is not known in advance. Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Repeat until the user has typed "q" to quit.

11 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while ( ) { ; } Example: int num = 1; // initialization while (num <= 200) { // test System.out.print(num + " "); num = num * 2; // update } // output:

12 Example while loop // finds a number's first factor other than 1 Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); int factor = 2; while (n % factor != 0) { factor++; } System.out.println("First factor is " + factor); while is better than for because we don't know how many times we will need to increment to find the factor

13 for vs. while loops The for loop is just a specialized form of the while loop. The following loops are equivalent: for (int num = 1; num <= 200; num = num * 2) { System.out.print(num + " "); } // actually, not a very compelling use of a while loop // (a for loop is better because the # of reps is definite) int num = 1; while (num <= 200) { System.out.print(num + " "); num = num * 2; }

14 sentinel: A value that signals the end of user input. sentinel loop: Repeats until a sentinel value is seen. Example: Write a program that prompts the user for text until the user types nothing, then output the total number of characters typed. (In this case, the empty string is the sentinel value.) Type a line (or nothing to exit): hello Type a line (or nothing to exit): this is a line Type a line (or nothing to exit): You typed a total of 19 characters. Sentinel values

15 Solution? Scanner console = new Scanner(System.in); int sum = 0; String response = "dummy"; // "dummy" value, anything but "" while (!response.equals("")) { System.out.print("Type a line (or nothing to exit): "); response = console.nextLine(); sum += response.length(); } System.out.println("You typed a total of " + sum + " characters.");

16 Changing the sentinel value Modify your program to use "quit" as the sentinel value. Example log of execution: Type a line (or "quit" to exit): hello Type a line (or "quit" to exit): this is a line Type a line (or "quit" to exit): quit You typed a total of 19 characters.

17 Changing the sentinel value Changing the sentinel's value to "quit" does not work! Scanner console = new Scanner(System.in); int sum = 0; String response = "dummy"; // "dummy" value, anything but "quit" while (!response.equals("quit")) { System.out.print("Type a line (or \"quit\" to exit): "); response = console.nextLine(); sum += response.length(); } System.out.println("You typed a total of " + sum + " characters."); This solution produces the wrong output. Why? You typed a total of 23 characters.

18 The problem with our code Our code uses a pattern like this: sum = 0. while (input is not the sentinel) { prompt for input; read input. add input length to the sum. } On the last pass, the sentinel’s length (4) is added to the sum: prompt for input; read input ( "quit" ). add input length (4) to the sum. This is a fencepost problem. Must read N lines, but only sum the lengths of the first N-1.

19 A fencepost solution sum = 0. prompt for input; read input.// place a "post" while (input is not the sentinel) { add input length to the sum.// place a "wire" prompt for input; read input.// place a "post" } Sentinel loops often utilize a fencepost "loop-and-a-half" style solution by pulling some code out of the loop.

20 Correct code Scanner console = new Scanner(System.in); int sum = 0; // pull one prompt/read ("post") out of the loop System.out.print("Type a line (or \"quit\" to exit): "); String response = console.nextLine(); while (!response.equals("quit")) { sum += response.length(); // moved to top of loop System.out.print("Type a line (or \"quit\" to exit): "); response = console.nextLine(); } System.out.println("You typed a total of " + sum + " characters.");

21 Sentinel as a constant public static final String SENTINEL = "quit";... Scanner console = new Scanner(System.in); int sum = 0; // pull one prompt/read ("post") out of the loop System.out.print("Type a line (or \"" + SENTINEL + "\" to exit): "); String response = console.nextLine(); while (!response.equals(SENTINEL)) { sum += response.length(); // moved to top of loop System.out.print("Type a line (or \"" + SENTINEL + "\" to exit): "); response = console.nextLine(); } System.out.println("You typed a total of " + sum + " characters.");

Procedural design reading: 4.5

23 Recall: BMI program Formula for body mass index (BMI): Write a program that produces output like the following: This program reads data for two people and computes their body mass index (BMI). Enter next person's information: height (in inches)? 70.0 weight (in pounds)? Enter next person's information: height (in inches)? 62.5 weight (in pounds)? Person 1 BMI = overweight Person 2 BMI = normal Difference = BMIWeight class below 18.5underweight normal overweight 30.0 and upobese

24 "Chaining" main should be a concise summary of your program. It is bad if each method calls the next without ever returning (we call this chaining): A better structure has main make most of the calls. Methods must return values to main to be passed on later. main methodA methodB methodC methodD main methodA methodB methodC methodD

25 Bad "chain" code public class BMI { public static void main(String[] args) { System.out.println("This program reads... (etc.)"); Scanner console = new Scanner(System.in); person(console); } public static void person(Scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextDouble(); getWeight(console, height); } public static void getWeight(Scanner console, double height) { System.out.print("weight (in pounds)? "); double weight = console.nextDouble(); computeBMI(console, height, weight); } public static void computeBMI(Scanner s, double h, double w) {... }

26 Procedural heuristics 1. Each method should have a clear set of responsibilities. 2. No method should do too large a share of the overall task. 3. Minimize coupling and dependencies between methods. 4. The main method should read as a concise summary of the overall set of tasks performed by the program. Sometimes this means you will put code other than method calls in main. This is OK, as long as you maintain good procedural design. 5. Data should be declared/used at the lowest level possible.

27 Open-ended BMI program Modify our BMI program to read user data and compute BMI’s until the user enters a weight below 0 (giving a negative BMI). This program reads data for people and computes their body mass index (BMI). Enter next person's information: Enter height in inches: 70.0 Enter weight in pounds (negative to quit): Person 1’s BMI = overweight Enter next person's information: Enter height in inches: 62.5 Enter weight in pounds (negative to quit): Person 2’s BMI = normal Enter height (in inches): 72 Enter weight (in pounds) - negative to quit: 225 Person 3's BMI = obese Enter next person's information: Enter height in inches: 65 Enter weight in pounds (negative to quit): -1 Goodbye!

28 Open-ended BMI program public class OpenEndedBMI { public static void main(String[] args) { introduction(); Scanner console = new Scanner(System.in); int person = 1; double bmi = processPerson(console); while (bmi >= 0) { report(person, bmi); person++; bmi = processPerson(console); } System.out.println("Goodbye!"); }...

29 Open-ended BMI program public static void introduction() { System.out.println("This program reads data for people and"); System.out.println("computes their body mass index (BMI)."); System.out.println(); } public static double processPerson(Scanner console) { System.out.println(); System.out.println("Enter next person's information"); System.out.print("Enter height in inches: "); double height = console.nextDouble(); System.out.print("Enter weight in pounds (negative to quit): "); double weight = console.nextDouble(); double bmi = (weight / (height * height)) * 703; return bmi; }...

30 Open-ended BMI program public static void report(int num, double bmi) { System.out.println("Person " + num + "'s BMI = " + bmi); if (bmi = 30.0) System.out.println("obese"); } } }