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.

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Building Java Programs
Building Java Programs Chapter 5
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may.
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.
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
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 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Random numbers. 2 The Random class A Random object generates pseudo-random numbers. –Class Random is found in the java.util package. import java.util.*;
Chapter 4: Control Structures II
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.
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.
1 Text processing Readings: Characters char : A primitive type representing single characters. Individual characters inside a String are stored.
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.
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.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers; Type boolean reading: , 5.6.
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.
1 Building Java Programs Chapter 5 Lecture 11: Random Numbers reading: 5.1, 5.6.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
Building Java Programs
Categories of loops definite loop: Executes a known number of times.
Lecture 5: Program Logic
Building Java Programs
Building Java Programs Chapter 5
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Building Java Programs
Chapter 5: Control Structures II
Repetition-Counter control Loop
Building Java Programs
CSC240 Computer Science III
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
Building Java Programs
Using Objects (continued)
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Indefinite loop variations
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

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 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.

3 Indefinite loops 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.

4 while loop 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 ( ) { ; } Example: int number = 1; while (number <= 200) { System.out.print(number + " "); number *= 2; } Output:

5 while loop flow chart

6 Example 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); Sample run: Type a number: 91 First factor: 7

7 for vs. while Any for loop of the following form: for ( ; ; ) { ; } is equivalent to a while loop of the following form: ; while ( ) { ; }

8 for vs. while : Example What while loop is equivalent to the following for loop? for (int i = 1; i <= 10; i++) { System.out.println(i + " squared = " + (i * i)); } Solution : int i = 1; while (i <= 10) { System.out.println(i + " squared = " + (i * i)); i++; }

9 Exercise 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: squared is 121

10 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(); } 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.

11 Exercise: 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: prints or 19 Hint: Use the % operator to extract the last digit of a number. If we do this repeatedly, when should we stop?

12 Solution: digitSum import java.util.Scanner; public class DigitSum { public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); int n = keyboard.nextInt(); int sum = 0; while (n > 0) { sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } System.out.println(“sum = “ + sum); }

13 Cumulative sum

14 Adding many numbers Consider the following code: Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int num1 = console.nextInt(); System.out.print("Type a number: "); int num2 = console.nextInt(); System.out.print("Type a number: "); int num3 = console.nextInt(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); Any ideas to improve the code?

15 Cumulative sum The variables num1, num2, and num3 are unnecessary: Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int sum = console.nextInt(); System.out.print("Type a number: "); sum += console.nextInt(); System.out.print("Type a number: "); sum += console.nextInt(); System.out.println("The sum is " + sum); 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: Scanner console = new Scanner(System.in); for (int i = 1; i <= 100; i++) { int sum = 0; System.out.print("Type a number: "); sum += console.nextInt(); } System.out.println("The sum is " + sum); 16 Cumulative sum

17 Cumulative sum loop A correct version: Scanner console = new Scanner(System.in); int sum = 0; for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum += console.nextInt(); } System.out.println("The sum is " + sum); 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.

18 User-guided cumulative sum The user's input can control the number of times the loop repeats: Scanner console = new Scanner(System.in); System.out.print("How many numbers to add? "); int count = console.nextInt(); int i = 1; int sum = 0; while(i <= count) { System.out.print("Type a number: "); sum += console.nextInt(); i++; } System.out.println("The sum is " + sum); Sample Run: How many numbers to add? 3 Type a number: 2 Type a number: 6 Type a number: 3 The sum is 11

19 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. Sample Run: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee's total paid hours = 19 Employee’s average paid hours =

20 Random numbers

21 The Random class 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 returns a random real number in the range [0.0, 1.0)‏ nextDouble()‏ returns a random integer in the range [0, max)‏ in other words, from 0 to one less than max nextInt( max )‏ returns a random integer nextInt()‏ DescriptionMethod name

22 Generating random numbers Random rand = new Random(); 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; What if we wanted a number from min to max (i.e. an arbitrary range)? int randomNum = rand.nextInt( ) + where equals ( )‏

23 Random questions Given the following declaration, how would you get: Random rand = new Random();  A random number between 0 and 100 inclusive?  A random number between 1 and 100 inclusive?  A random number between 4 and 17 inclusive?

24 Random solutions Given the following declaration, how would you get: Random rand = new Random();  A random number between 0 and 100 inclusive? int random1 = rand.nextInt(101);  A random number between 1 and 100 inclusive? int random1 = rand.nextInt(100) + 1;  A random number between 4 and 17 inclusive? int random1 = rand.nextInt(14) + 4;

25 Exercise: Die-rolling Write a program that simulates the rolling of two six-sided dice until their combined result comes up as 7. Sample run: Roll: = 6 Roll: = 8 Roll: = 11 Roll: = 2 Roll: = 7 You won after 5 tries!

26 Solution: Die-rolling import java.util.*; public class Roll { public static void main(String[] args) { Random rand = new Random(); int sum = 0; 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!"); }

27 Indefinite loop variations

28 Variant 1: do / while 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 ( ); Example: // roll until we get a number other than 3 Random rand = new Random(); int die; do { die = rand.nextInt(); } while (die == 3);

29 do / while loop flow chart How does this differ from the while loop?  The controlled will always execute the first time, regardless of whether the is true or false.

30 Variant 2: "Forever" loops Loops that go on… forever while (true) { ; } If it goes on forever, how do you stop?

31 break ing the cycle break statement: Immediately exits a loop ( for, while, do / while ). Example: while (true) { ; if ( ) { break; } ; } Why is the break statement in an if statement?

32 Revisiting the sentinel problem Sentinel loop using break : Scanner console = new Scanner(System.in); int sum = 0; 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);