! 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

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Text processing. Readings: 4.4

Building Java Programs

Building Java Programs

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

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

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Building Java Programs Chapter 5

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

CS 112 Introduction to Programming

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Building Java Programs

Conditional Execution

CS 112 Introduction to Programming

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

Topic 11 Scanner object, conditional execution

Repetition, Looping. While Loop

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

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

Topic 11 Scanner object, conditional execution

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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.

Building Java Programs

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Chapter 4: Control Structures I

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

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

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

Topic 14 while loops and loop patterns

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Midterm Examination (MTA)

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

St. Edmund Preparatory High School Brooklyn, NY

Object Oriented Programming. Java-Lecture 6 - Arrays

AP Computer Science Unit 1. Programs

Java Coding 3. Over & over again!

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Last Class. While loops Infinite loops Loop counters Iterations

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

What two elements are usually present for calculating a total of a series of numbers?

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

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

Building Java Programs

Assignment 2.4: Loops

Repetition Structures

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

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Building Java Programs

Fundamentals of Programming Data Types & Methods

CS 112 Introduction to Programming

COMP 202 Java in one week

assertion: A statement that is either true or false.

CSC 1051 Data Structures and Algorithms I

Chapter 3. Selections

1 Short Answer (5 Points Each)

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Chapter 1 Lab Algorithms, Errors, and Testing

IT 1033: Fundamentals of Programming Loops

COMP 202. Java in one week

Introduction to the Java Basics: Control Flow Statements

Program Control Flow

Program Control Flow

Full file at

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

Full file at

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

REPETITION CONTROL STRUCTURE LOGO

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Repetition. Chapter 6

Building Java Programs

3 The L oop Control Structure

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Repetition. Chapter 6

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

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

COMP-202 Unit 4: Programming with Iterations

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

A token is a sequence of characters not including any whitespace.

Repetition with for loops

Advanced if/else & Cumulative Sum

Building Java Programs

Computational Expression

COMP 110 Programming Exercise: Simulation of the Game of Craps

A+ Computer Science -

Chapter 4: Conditionals and Recursion

1 Short Answer (10 Points Each)

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section

Conditional Programming

Topic 12 more if/else, cumulative algorithms, printf

Transcription:

Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is still true." " "Don't stop repeating until the following happens."! Examples: " Print random numbers until a prime number is printed. " Continue looping while the user has not typed "n" to quit.! while loop: A control structure that repeatedly performs a test and executes a group of statements if the test evaluates to true.! while loop, general syntax: while (<test>) {! Example: int number = 1; while (number <= 200) { System.out.print(number + " "); number *= 2; Output: 1 2 4 8 16 32 64 128 3 4 Definite loops while loops! 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 " "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. 1 2

for vs. while for vs. while: Example! Any for loop of the following form: for (<initialization>; <test>; <update>) { is equivalent to a while loop of the following form: <initialization>; while (<test>) { <update>;! What while loop is equivalent to the following for loop? for (int i = 1; i <= 10; i++) { Solution: System.out.println(i + " squared = " + (i * i)); int i = 1; while (i <= 10) { System.out.println(i + " squared = " + (i * i)); i++; 7 8 while loop flow chart Example! Finds and prints a number's first factor other than 1: int number = console.nextint(); int factor = 2; while (number % factor!= 0) { factor++; System.out.println("First factor: " + factor); Sample run: Type a number: 91 First factor: 7 5 6

Exercise: digitsum Solution: digitsum! Write a class named DigitSum that reads an integer from the user and prints the sum of the digits of that number. You may assume that the number is non-negative. Example: Enter a nonnegative number: 29107 prints 2+9+1+0+7 or 19! Hint: Use the % operator to extract the last digit of a number. If we do this repeatedly, when should we stop? 11 import java.util.scanner; public class DigitSum { public static void main(string [] args) { Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); while (n > 0) { sum += n % 10; // add last digit to sum n = n / 10; // remove last digit System.out.println(!sum =! + sum); 12 Exercise Solution! Write a program that will repeatedly prompt the user to type a number until the user types a non-negative number, then square it. Example log: 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: 11 11 squared is 121 9 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(); int square = number * number; System.out.println(number + " squared is " + square);! Notice that the number variable had to be declared outside the while loop in order to remain in scope. 10

Cumulative sum Cumulative sum! The variables num1, num2, and num3 are unnecessary: int sum = console.nextint();! cumulative sum: A variable that keeps a sum-in-progress and is updated many times until the task of summing is finished. " The variable sum in the above code represents a cumulative sum.! How could we modify the code to sum 100 numbers? " Creating 100 copies of the same code would be redundant.! An incorrect solution: for (int i = 1; i <= 100; i++) { 15 16 Adding many numbers Cumulative sum! Consider the following code: int num1 = console.nextint(); int num2 = console.nextint(); int num3 = console.nextint(); int sum = num1 + num2 + num3;! Any ideas to improve the code? 13 14

Cumulative sum: Exercise! Write a program that reads input of the number of hours an employee has worked and displays the employee's total and average (per day) number of hours. " The company doesn't pay overtime, so cap any day at 8 hours. Random numbers Sample Run: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee's total paid hours = 19 Employee!s average paid hours = 6.3333333 19 20 Cumulative sum loop User-guided cumulative sum! A correct version: for (int i = 1; i <= 100; i++) {! Key idea: Cumulative sum variables must always be declared outside the loops that update them, so that they will continue to live after the loop is finished. 17! The user's input can control the number of times the loop repeats: System.out.print("How many numbers to add? "); int count = console.nextint(); int i = 1; while(i <= count) { i++; Sample Run: How many numbers to add? 3 Type a number: 2 Type a number: 6 Type a number: 3 The sum is 11 18

Random questions Random solutions! Given the following declaration, how would you get: " A random number between 0 and 100 inclusive?! Given the following declaration, how would you get: " A random number between 0 and 100 inclusive? int random1 = rand.nextint(101); " A random number between 1 and 100 inclusive? " A random number between 1 and 100 inclusive? int random1 = rand.nextint(100) + 1; " A random number between 4 and 17 inclusive? 23 " A random number between 4 and 17 inclusive? int random1 = rand.nextint(14) + 4; 24 The Random class Generating random numbers! Objects of the Random class generate pseudo-random numbers. " Class Random is found in the java.util package. import java.util.*;! The methods of a Random object int randomnum = rand.nextint(10); // randomnum has a random value between 0 and 9! What if we wanted a number from 1 to 10? int randomnum = rand.nextint(10) + 1; Method name nextint()! nextint(max)! nextdouble()! Description returns a random integer ( max returns a random integer in the range [0, in other words, from 0 to one less than max ( 1.0 [0.0, range returns a random real number in the 21! What if we wanted a number from min to max (i.e. an arbitrary range)? int randomnum = rand.nextint(<size of the range>) + <min> ( 1 + <min> where <size of the range> equals (<max> - 22

Variant 1: do/while Indefinite loop variations! do/while loop: A control structure that executes statements repeatedly while a condition is true, testing the condition at the end of each repetition.! do/while loop, general syntax: do { while (<test>);! Example: // roll until we get a number other than 3 int die; do { die = rand.nextint(); while (die == 3); 27 28 Exercise: Die-rolling Solution: Die-rolling! Write a program that simulates the rolling of two six-sided dice until their combined result comes up as 7. import java.util.*; public class Roll { public static void main(string[] args) { Sample run: Roll: 2 + 4 = 6 Roll: 3 + 5 = 8 Roll: 5 + 6 = 11 Roll: 1 + 1 = 2 Roll: 4 + 3 = 7 You won after 5 tries! int tries = 0; while (sum!= 7) { int roll1 = rand.nextint(6) + 1; int roll2 = rand.nextint(6) + 1; sum = roll1 + roll2; System.out.println("Roll: " + roll1 + " + " + roll2 + " = " + sum); tries++; System.out.println("You won after " + tries + " tries!"); 25 26

breaking the cycle Revisiting the sentinel problem! break statement: Immediately exits a loop (for, while, do/while).! Example: while (true) { if (<test>) { break;! Why is the break statement in an if statement? 31! Sentinel loop using break: while (true) { System.out.print("Enter a number (-1 to quit): "); int inputnumber = console.nextint(); if (inputnumber == -1) { // don't add -1 to sum break; sum += inputnumber; // inputnumber!= -1 here System.out.println("The total was " + sum); 32 do/while loop flow chart Variant 2: "Forever" loops! How does this differ from the while loop? " The controlled <statement(s)> will always execute the first time, regardless of whether the <test> is true or false.! Loops that go on! forever while (true) {! If it goes on forever, how do you stop? 29 30