Building Java Programs

Slides:



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

Building Java Programs
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.
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.
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.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
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.
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.
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.
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.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Cumulative algorithms. 2 Adding many numbers How would you find the sum of all integers from ? // This may require a lot of typing int sum = 1 +
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.
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.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
CS 112 Introduction to Programming Program Analysis; Fencepost Loops Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Building Java Programs
CSc 110, Autumn 2017 Lecture 15: Strings and Fencepost Loops
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
Lecture 5: Program Logic
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Lecture 7: Input and Miscellaneous
Chapter 5: Control Structures II
Repetition-Counter control Loop
Building Java Programs Chapter 5
Building Java Programs Chapter 5
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
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
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
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
Presentation transcript:

Building Java Programs Chapter 5: Program Logic and Indefinite Loops

Lecture outline fencepost loops indefinite loops the while loop sentinel loops

Fencepost loops reading: 4.1

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

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, System.out.print(", " + i); , 1, 2, 3, 4, 5

Fence post analogy We print n numbers but need only n - 1 commas. This problem is similar to the task of building a fence with lengths of wire separated by posts. often called a fencepost problem If we repeatedly place a post and wire, the last post will have an extra dangling wire. A flawed algorithm: for (length of fence) { place some post. place some wire. }

Fencepost loop The solution is to add an extra statement outside the loop that places the initial "post." This is sometimes also called a fencepost loop or a "loop-and-a-half" solution. The revised algorithm: place a post. for (length of fence - 1) { place some wire. place some post. }

Fencepost method solution A version of printNumbers that works: 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 of output Output from printNumbers(5): 1, 2, 3, 4, 5

Fencepost question Write a method named printPrimes that, when given a maximum number, prints all prime numbers up to that maximum in the following format. Example: printPrimes(50) prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Fencepost answer public class Primes { public static void main(String[] args) { printPrimes(50); printPrimes(1000); } // 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("]"); // see ch04-1 slides for countFactors method

while loops reading: 5.1

Definite loops definite loop: One that executes a known number of times. The for loops we have seen so far are definite loops. We often use language like, "Repeat these statements N times." "For each of these 10 things, ...." Examples: Print "hello" 10 times. Find all the prime numbers up to an integer n. Print each odd number between 5 and 127.

Indefinite loops indefinite loop: One where it is not obvious in advance how many times it will execute. The while loops in this chapter are indefinite loops. We often use language like, "Keep looping as long as or while this condition is still true." "Don't stop looping until the following happens." Examples: Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Continue looping while the user has not typed "n" to quit.

The while loop statement while loop: Executes as long as a condition is true. well suited to writing indefinite loops while (<condition>) { <statement(s)> ; } Example: int number = 1; while (number <= 200) { System.out.print(number + " "); number = number * 2; OUTPUT: 1 2 4 8 16 32 64 128

Example while loop Finds and prints 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 (number % factor != 0) { factor++; } System.out.println("First factor: " + factor); Example log of execution: Type a number: 91 First factor: 7

While loop question Write code that repeatedly prompts until the user types a non-negative number, then computes its square root. Example log of execution: Type a non-negative integer: -5 Invalid number, try again: -1 Invalid number, try again: -235 Invalid number, try again: -87 Invalid number, try again: 121 The square root of 121 is 11.0

While loop answer Solution: System.out.print("Type a non-negative integer: "); int number = console.nextInt(); while (number < 0) { System.out.print("Invalid number, try again: "); number = console.nextInt(); } System.out.println("The square root of " + number + " is " + Math.sqrt(number)); Notice that number has to be declared outside the loop.

Sentinel loops reading: 5.1

Sentinel values sentinel: Special value that signals the end of user input. sentinel loop: Repeats until a sentinel value is seen. Example: Write a program that repeatedly prompts the user for numbers to add until the user types 0, then outputs their sum. (In this case, 0 is our sentinel value.) Example log of execution: Enter a number (0 to quit): 95 Enter a number (0 to quit): 87 Enter a number (0 to quit): 42 Enter a number (0 to quit): 26 Enter a number (0 to quit): 0 The total is 250

Flawed sentinel solution What's wrong with this solution? Scanner console = new Scanner(System.in); int sum = 0; int number = 1; // "dummy value", anything but 0 while (number != 0) { System.out.print("Enter a number (0 to quit): "); number = console.nextInt(); sum = sum + number; } System.out.println("The total is " + sum);

A different sentinel value Modify your program to use a sentinel value of -1. Example log of execution: Enter a number (-1 to quit): 95 Enter a number (-1 to quit): 87 Enter a number (-1 to quit): 42 Enter a number (-1 to quit): 26 Enter a number (-1 to quit): -1 The total is 250

Changing the sentinel value To see the problem, change the sentinel's value to -1: Scanner console = new Scanner(System.in); int sum = 0; int number = 1; // "dummy value", anything but -1 while (number != -1) { System.out.print("Enter a number (-1 to quit): "); number = console.nextInt(); sum += number; } System.out.println("The total is " + sum); Now the solution produces the wrong output. Why? The total was 249

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 to the sum. } On the last pass, the sentinel -1 is added to the sum: prompt for input; read input (-1). add input (-1) to the sum. This is a fencepost problem. We want to read N numbers, but only sum the first N-1 of them.

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

Correct code This solution produces the correct output: Scanner console = new Scanner(System.in); int sum = 0; System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); while (number != -1) { sum = sum + number; // moved to top of loop number = console.nextInt(); } System.out.println("The total is " + sum);

Constant with sentinel A better solution creates a constant for the sentinel: public static final int SENTINEL = -1; This solution uses the constant: Scanner console = new Scanner(System.in); int sum = 0; System.out.print("Enter a number (" + SENTINEL + " to quit): "); int number = console.nextInt(); while (number != SENTINEL) { sum = sum + number; number = console.nextInt(); } System.out.println("The total is " + sum);