CS 112 Introduction to Programming Loop Patterns: break; Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Slides:



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

Building Java Programs
Computer Science 1620 Loops.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
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.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Copyright 2008 by Pearson Education 1 Midterm announcements Next week on Friday May 8 Must bring an ID Open book, open notes, closed electronics Must attend.
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
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.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
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.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS 112 Introduction to Programming Program Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Chapter 4: Control Structures II
Building java programs, chapter 5 Program logic and indefinite loops.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
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.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
CS 112 Introduction to Programming Program Analysis; Fencepost Loops Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Categories of loops definite loop: Executes a known number of times.
CSc 110, Autumn 2017 Lecture 17: while Loops and Sentinel Loops
Chapter 5: Control Structures II
Repetition-Counter control Loop
Chapter 5: Control Structures II
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
Building Java Programs
Building Java Programs
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
Control Statements Loops.
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
Building Java Programs
Building Java Programs
Control Statements Loops.
Repetition Statements
Building Java Programs
Building Java Programs
Indefinite loop variations
Building Java Programs
Building Java Programs
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
Presentation transcript:

CS 112 Introduction to Programming Loop Patterns: break; Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

2

Exercise: MatchDB  Design a program to query a match-making database m database (file) format: line 1: number of candidates each line represents a candidate: name age and then a sequence of words (tags) each describing a character m user commands list: display each candidate count // count # matching all tags match1 // print first record that matches all tags match // print matched record to record … 3

match1 public static void match1 (String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); } } // end of for } Problem: Loop does not stop after matching first.

Solution I: Using break  break statement: Immediately exits a loop. m Can be used to write a loop whose test is in the middle. loop over elements { ; if ( ) { // do something break; } ; }  Typical in a search problem m Find what you are looking for, i.e., an “evidence”  Exercise: fix match1 using break

Removing break  Using break to jump out of a loop is considered a bad style by some programmers Multiple exit points Objective: design a single exit point. public static void match1(String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); break; } } // end of for }

Analysis  Question: logical conditions that the for loop should exit? 7 i >= N || matchTags(mTags, i) Condition to continue the loop (negate of the above): !( i >= N || matchTags(mTags, i) ) public static void match1(String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); break; } } // end of for }

De Morgan's Law  De Morgan's Law: Rules used to negate boolean tests. m Useful when you want the opposite of an existing test. Original ExpressionNegateEquivalent Negate a && b!(a && b)!a || !b a || b!(a || b)!a && !b i < N && ! checkMatch(mTags, i) !( i >= N || checkMatch(mTags, i) )

Revised Version w/o break: II 9 public static void match1(String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); break; } } // end of for } public static void match1(String[] mTags){ for (int i = 0; i < N && !checkMatch(mTags, i) ; i++ ) { } // end of for }

Revised Version w/o break: II 10 public static void match1(String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); break; } } // end of for } public static void match1(String[] mTags){ int i = 0; for (; i < N && !checkMatch(mTags, i) ; i++ ) { } // end of for } if (i < N) System.out.println(“Find ” + name[i]);

Revised Version w/o break: II 11 reads ugly public static void match1(String[] mTags){ int i; for (i = 0; i < N && !checkMatch(mTags, i) ; i++ ) { } // end of for } if (i < N) System.out.println(“Find ” + name[i]);

Revised Version w/o break: II 12 public static void match1(String[] mTags){ for (int i = 0; i < N; i++ ) { if ( checkMatch(mTags, i) ) { System.out.println(“Find ” + name[i]); break; } }} public static void match1(String[] mTags){ int i; for (i = 0; i < N && !checkMatch (mTags, i) ; i++ ) { } // end of for } if (i < N) System.out.println(“Find ” + name[i]); public static void match1(String[] mTags){ int i = 0; while (i < N && !checkMatch(mTags, i) ) { i++; } if (i < N) System.out.println(“Find ” + name[i]);

Practice  Implement the match command: match

Roadmap: Program Flow Control Deterministic for loop (loop counter) cumulative scan loop Early exit loops Fencepost loops

15 Example Problem: User Input Protocol  Two input styles m Header control protocol User first specifies the number of data items m In-band control protocol User finishes input by entering a sentinel value –e.g., -1 to signal the end of input grades; “quit” to finish the program Why in-band sentinel: flexibility. Implication: a data item just read can be either a real data item or the signaling sentinel N data 1 data N data || control

 sentinel: A value that signals the end of user input. m 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 outputs the total number of characters typed. m (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 Design question: for, while, or do loop?

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

Changing the Sentinel Value  Changing the sentinel's value to "quit" Scanner console = new Scanner(System.in); int sum = 0; String response; do { System.out.print("Type a line (or \"quit\" to exit): "); response = console.nextLine(); sum += response.length(); } while ( !response.equals("quit”); System.out.println("You typed a total of " + sum + " characters."); 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  This solution produces the wrong output. Why? You typed a total of 23 characters.

A “Simpler” Problem...  Revisit the countDown method that prints from a given maximum (>=1) to 1, separated by commas. For example, the call: countDown(5) should print: 5, 4, 3, 2, 1

Previous “Solution”  public static void countDown(int max) { for (int i = max; i >= 1; i--) { System.out.print(i + ", "); } System.out.println(); // to end the line of output }  Output from countDown(5) :  public static void countDown(int max) { for (int i = max; i >= 1; i--) { System.out.print(", " + i); } System.out.println(); // to end the line of output }  Output from countDown(5) :, 5, 4, 3, 2, 1 5, 4, 3, 2, 1, 5, 4, 3, 2, 1

Problem: Fence Post Analogy  We print n numbers but need only n - 1 commas.  If we use a loop algorithm that repeatedly places a post + wire, the last post will have an extra dangling wire. loop (length of fence-wire pair) { place a post. // e.g., place some wire. // e.g.,, } 5, 4, 3, 2, 1,

Problem: Fence Post Analogy Scanner console = new Scanner(System.in); int sum = 0; String response; do { System.out.print("Type a line (or \"quit\" to exit): "); response = console.nextLine(); sum += response.length(); } while ( !response.equals("quit”); System.out.println("You typed a total of " + sum + " characters."); 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 23 characters. The sentinel read is also a fencepost problem: Must read N lines, but sum only the lengths of the first N-1.

Fencepost Loop Solution  There are multiple solutions  A typically one is to add a statement outside the loop to place the initial "post.” Also called a "loop-and- a-half" solution. place a post. loop (length of fence - 1) { place some wire. place a post. }

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

Fencepost Sentinel Loop public static final String SENTINEL = "quit"; public static final String PROMPT = "Type a line (or \"" + SENTINEL + "\" to exit): “; public static Count() { Scanner console = new Scanner(System.in); int sum = 0; // pull one prompt/read ("post") out of the loop String response = getString(PROMPT, console); while ( !response.equals(SENTINEL) ) { sum += response.length(); // wire response = getString(PROMPT, console); // post } System.out.println("You typed a total of " + sum + " characters before quit."); } public static String getString(String prompt, Scanner console) { System.out.print(prompt); return console.nextLine(); } Define as constants

Fencepost Sentinel Loop: Grade public static final int SENTINEL = -1; public static final String PROMPT = "Type a grade (" + SENTINEL + ” to exit): “; public static GradeAnalyzer() { Scanner console = new Scanner(System.in); int sum = 0; int count = 0; // pull one prompt/read ("post") out of the loop int grade = getInt(PROMPT, console); while ( grade != SENTINEL ) { sum += grade; count++; // wire grade = getInt(PROMPT, console); // post } if (count > 0) System.out.println(”Avg: ” 1.0 * sum / count); } public static String getInt(String prompt, Scanner console { System.out.print(prompt); return console.nextInt(); }

Summary: Fencepost Loops 27 read a number update sum int sum = 0; int count = 0; System.out.print("Enter a number (-1 to quit): "); int grade = console.nextInt(); while ( grade != -1 ) { sum = sum + grade; count ++; System.out.print("Enter a number (-1 to quit): "); grade = console.nextInt(); }

Alternative Design: Motivation place a post. loop (length of fence - 1) { place a wire. place a post. } Some programmers feel “heart-broken” to see this “redundancy” not removed by loop

Alternative Design loop (length of fence) { place a post. if (! last post) place a wire. } Detect if it is the last post in the loop, if it is, do not place the wire place a post loop (length of fence-1) { place a wire. place a post }

Alternative Design Scanner console = new Scanner(System.in); int sum = 0; int grade = 0; while ( grade != -1 ) { // post System.out.print("Enter a number (-1 to quit): "); grade = console.nextInt(); if ( grade != -1 ) { // detect the last post sum = sum + grade; // wire } } System.out.println("The total was " + sum);

Comparison int sum = 0; int grade = 0; while ( grade != -1 ) { System.out.print("Enter a number (-1 to quit): "); grade = console.nextInt(); if ( grade != -1 ) { // detect the last post sum = sum + grade; } int sum = 0; System.out.print("Enter a number (-1 to quit): "); int grade = console.nextInt(); while ( grade != -1 ) { sum = sum + grade; System.out.print("Enter a number (-1 to quit): "); grade = console.nextInt(); } Duplicated code Duplicate execution

Alternative Design: Analysis int sum = 0; int grade = 0; while ( grade != -1 ) { System.out.print("Enter a number (-1 to quit): "); grade = console.nextInt(); if ( grade != -1 ) { // detect the last post sum = sum + grade; } So that we can exit the loop So that we don’t have an extra wire Q: Can we remove the duplication, say the first test?

Sentinel Loop with break Scanner console = new Scanner(System.in); int sum = 0; while (true) { System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); if (number == -1) { // detect the last post break; } sum = sum + number; // number != -1 here } System.out.println("The total was " + sum);

Comments  Choice between “sentinel loop with break” vs “non- break ” is typically a personal style  The “non- break ” version may be preferred, because m the high-level structure (“topical sentence”) indicates that the loop is controlled by a sentinel m the high-level structure (“topical sentence”) of the “break” version indicates that the loop is an infinite loop. 34

Refining GradeAnalyzer  Problem statement: users are known to give wrong input. A rule of robust programming is to remember Murphy’s Law  What may be wrong when a user gives an input for a grade? m Not a valid integer m Not in the right range 35

Step 1: getInt  Write a method getInt to read an integer. If the user does not give an integer, output an error message that we are reading an integer, and ask again. 36 print prompt output format error message; discard input

getInt() public static int getInt(Scanner console, String prompt) { System.out.print(prompt); while ( !console.hasNextInt() ) { console.next(); System.out.println("That is not an integer. " + "Please try again."); System.out.print(prompt); } return console.nextInt(); } 37

Step 2: Application Logic Validation  Even when the user gives an integer, it may not be a valid grade input, i.e. -1 or between 59 and 100 for “the new grading system” that Yale is considering.  Write a method getGrade to read a valid integer for a grade. If the user does not give a valid integer, output an error message indicating invalid range, and repeat. 38 getInt output range error message

getGrade() public static int getGrade(Scanner console, String prompt) { int grade = getInt(console, prompt); while ( !(grade == -1 || 59 <= grade && grade <=100) ) { System.out.println(“Input is not valid."); grade = getInt(console, prompt); } return grade; } 39

getGrade() using Break public static int getGrade(Scanner console, String prompt) { int grade; while ( true ) { grade = getInt(console, prompt); if (grade == -1 || grade >= 59 && grade <= 100) { break; } System.out.println(“Input grade not valid."); } return grade; } 40