Building Java Programs

Similar documents
Topic 14 while loops and loop patterns

Building Java Programs

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

Building Java Programs

Building Java Programs Chapter 5

Building Java Programs

Building Java Programs

assertion: A statement that is either true or false.

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Lecture 6: While Loops and the Math Class

CS 112 Introduction to Programming

Midterm Examination (MTA)

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Text processing. Readings: 4.4

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I

Full file at

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

Advanced if/else & Cumulative Sum

Loops / Repetition Statements

Chapter 2: Basic Elements of Java

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Repetition, Looping. While Loop

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

How would you handle the case for when a user selects an option? 1/15/2016 CSE 11 WINTER LEC 6 2

Chapter 4: Control Structures I

Building Java Programs

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Java Coding 3. Over & over again!

Building Java Programs

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

AP CS Unit 3: Control Structures Notes

Topic 12 more if/else, cumulative algorithms, printf

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Loops. Repeat after me

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Topic 12 more if/else, cumulative algorithms, printf

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Conditional Execution

Topic 11 Scanner object, conditional execution

Building Java Programs

Repetition CSC 121 Fall 2014 Howard Rosenthal

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 4: Control structures. Repetition

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

St. Edmund Preparatory High School Brooklyn, NY

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Chapter 4: Control structures

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Final Examination Semester 2 / Year 2011

Over and Over Again GEEN163

CS141 Programming Assignment #6

Midterm Review Session

Topic 11 Scanner object, conditional execution

CPSC 219 Extra review and solutions

Assignment 2.4: Loops

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018

Building Java Programs

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CSC 1051 Data Structures and Algorithms I

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Last Class. While loops Infinite loops Loop counters Iterations

Loops. CSE 114, Computer Science 1 Stony Brook University

Top-Down Program Development

CompSci 125 Lecture 11

Building Java Programs

11.3 Function Prototypes

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CS111: PROGRAMMING LANGUAGE II

Building Java Programs

Building Java Programs

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Introduction to Computer Programming

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Introduction to Java & Fundamental Data Types

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Building Java Programs

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Building Java Programs

Building Java Programs

Building Java Programs Chapter 2

Transcription:

Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009 by Pearson Education

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 Copyright 2009 by Pearson Education 2

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 Copyright 2009 by Pearson Education 3

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 repeatedly place a post + wire, the last post will have an extra dangling wire. A flawed algorithm: for (length of fence) { place a post. place some wire. Copyright 2009 by Pearson Education 4

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. The revised algorithm: place a post. for (length of fence - 1) { place some wire. place a post. Copyright 2009 by Pearson Education 5

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 Copyright 2009 by Pearson Education 6

while loops reading: 5.1 self-check: 1-10 exercises: 1-2 Copyright 2009 by Pearson Education

Categories of loops definite loop: Executes a known number of times. The for loops we have seen are definite loops. Examples: 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. Examples: Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Repeat until the user has types "q" to quit. Copyright 2009 by Pearson Education 8

The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s); Example: int num = 1; while (num <= 200) { System.out.print(num + " "); num = num * 2; OUTPUT: 1 2 4 8 16 32 64 128 // initialization // test // update Copyright 2009 by Pearson Education 9

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 (number % factor!= 0) { factor++; System.out.println("First factor: " + factor); Example log of execution: Type a number: 91 First factor: 7 while is better than for here because we don't know how many times we will need to increment to find the factor. Copyright 2009 by Pearson Education 10

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; Copyright 2009 by Pearson Education 11

while and Scanner while loops are often used with Scanner input. You don't know many times you'll need to re-prompt the user if they type bad data. (an indefinite loop!) 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 Copyright 2009 by Pearson Education 12

while loop answer 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. Copyright 2009 by Pearson Education 13

Sentinel loops reading: 5.1 self-check: 5 exercises: 1, 2 Copyright 2009 by Pearson Education

Sentinel values sentinel: A 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 until the user types 0, then outputs their sum. (In this case, 0 is the sentinel value.) 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 Copyright 2009 by Pearson Education 15

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); Copyright 2009 by Pearson Education 16

A different sentinel value Modify your program to use a sentinel value of -1. 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 Copyright 2009 by Pearson Education 17

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 Copyright 2009 by Pearson Education 18

The problem 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 must read N numbers, but only sum the first N-1 of them. Copyright 2009 by Pearson Education 19

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

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 System.out.print("Enter a number (-1 to quit): "); number = console.nextint(); System.out.println("The total is " + sum); Copyright 2009 by Pearson Education 21

Constant with sentinel A better solution uses 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; System.out.print("Enter a number (" + SENTINEL + " to quit): "); number = console.nextint(); System.out.println("The total is " + sum); Copyright 2009 by Pearson Education 22