Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.

Slides:



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

Building Java Programs
Building Java Programs Chapter 5
Building Java Programs
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
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.
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
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Copyright 2009 by Pearson Education Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos: Ch.
Java Programming: From the Ground Up
Chapter 5 Loops.
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.
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.*;
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
Chapter 5: Control Structures II
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
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.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
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.
The for loop.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
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.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Building Java Programs
Chapter 5: Control Structures II
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
CSC240 Computer Science III
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Topic 14 while loops and loop patterns
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSC115 Introduction to Computer Programming
Building Java Programs
The for loop suggested reading:
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
Chapter 2 Lecture 2-2: The for Loop reading: 2.3
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1

Table of Contents Taste of Loop While Loop Do While Loop For Loop Variations Controlling Number of Loop Iterations Loop Development Mapping Iterations to Counter Values Controlling Event of Loop Iterations Random number generator Fencepost problem (an interesting scenario) Summary of Learning Materials 2

Price is right. Sample execution (click on this link to try)this link Before you get the price right, the program will REPEAT… Taste of Loop 3

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:

The prepares the variable declarations and their values that are used in the test, update, and body of the loop. The checks whether the repetition of the loop body can stop. The statement or group of statements to be repeated is called the of the loop. Each repetition of the loop body is called an of the loop. 5

; while ( ) { ; } 6

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

Example, WhileDemo.java, P202, WhileDemo.java 8

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); 9

How does this differ from the while loop? The controlled will always execute the first time, regardless of whether the is true or false. 10

Example, DoWhileDemo.java, P206, DoWhileDemo.java 11

for loop: A block of Java code that executes a group of statements repeatedly until a given test fails. General syntax: for ( ; ; ) { ;... ; } Example: for (int i = 1; i <= 30; i++) { System.out.println("I will not throw..."); } Variant 2: for 12

for ( ; ; ) { ; } 13

Example, ForDemo.java, P219, ForDemo.java 14

Summary Body first, and then event change/update 15

16

17

18

Initialization, test, and body, and execution results of loop 19 Code: for (int i = 1; i <= 4; i++) { System.out.println(i + " squared is " + (i * i)); } Output: 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16

Variations The initial and final values for the loop counter/event variable can be arbitrary expressions: Example: for (int i = -3; i <= 2; i++) { System.out.println(i); } Output: Example: for (int i = * 4; i <= 5248 % 100; i++) { System.out.println(i + " squared is " + (i * i)); } 20

The update can be a -- (or any other operator). Caution: This requires changing the test from =. System.out.println("T-minus"); for (int i = 3; i >= 1; i--) { System.out.println(i); } System.out.println("Blastoff!"); Output: T-minus Blastoff! 21

What if we wanted the output to be the following? T-minus Blastoff! System.out.print prints the given output without moving to the next line. System.out.print("T-minus "); for (int i = 3; i >= 1; i--) { System.out.print(i + " "); } System.out.println("Blastoff!"); 22

When controlling a single statement, the {} braces are optional. for (int i = 1; i <= 6; i++)‏ System.out.println(i + " squared is " + (i * i)); This can lead to errors if a line is not properly indented. for (int i = 1; i <= 3; i++)‏ System.out.println("This is printed 3 times"); System.out.println("So is this... or is it?"); Output: This is printed 3 times So is this... or is it? Moral: Always use curly braces and always use proper indentation. 23

Extra semicolon in a loop (P218). int i; for (i = 1; i <= 6; i++)‏; System.out.println(i + " squared is " + (i * i)); Output: 7 squared is 49 Comman in a loop (P220). int i, sum; for (i = 1, sum = 0; i <= 10; i++)‏ sum = sum + i * i; System.out.println("Result is " + sum); Output: 385 int sum; for (int i=0, sum; … 24

Invalidation: Loops that never execute. for (int i = 10; i < 5; i++) { System.out.println("How many times do I print?"); } ERROR: Loop tests that never fail. A loop that never terminates is called an infinite loop. for (int i = 10; i >= 1; i++) { System.out.println("Runaway Java program!!!"); } 25

Loops that go on… forever while (true) { ; } If it goes on forever, how do you stop? 26

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

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); 28

Special case: If a variable is declared in the part of a for loop, its scope is the for loop. public static void main(String [] args) { int x = 3; int i; for (i = 1; i <= 10; i++) { System.out.println(x); } // i no longer exists here } // x ceases to exist here x's scope i’s scope 29

ERROR: Using a variable outside of its scope. public static void main(String[] args) { for (int i = 1; i <= 10; i++) { int y = 5; System.out.println(y); } System.out.println(i); // illegal System.out.println(y); // illegal } 30

COMMON ERROR: Using the wrong loop counter variable. But barely possible when you develop code with our process. What is the output of the following piece of code? for (int i = 1; i <= 10; i++) { for (int j = 1; i <= 5; j++) { System.out.print(j); } System.out.println(); } What is the output of the following piece of code? for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; i++) { System.out.print(j); } System.out.println(); } 31

3211/29/2015 Exercises

Loop Development 33 population TV purchase

34

Controlling Number of Loop Iterations If the number of iterations is known before the loop starts, the loop is called a count- controlled loop. Counter =0, counter++, counter <number Counter = 1, counter++, counter <=number Use for loop for an easy development. 35

36

37

Mapping iterations to counter values Suppose that we have the following loop: for (int count = 0; count < 49; count++) {... } What statement could we write in the body of the loop that would make the loop print the following output? … Answer: for (int count = 0; count < 49; count++) { System.out.print(2 * count + " "); } 38

Now consider another loop of the same style: for (int count = 0; count < 49; count++) {... } What statement could we write in the body of the loop that would make the loop print the following output? Answer: for (int count = 0; count < 49; count++) { System.out.print(2 * count " "); } 39

What statement could we write in the body of the loop that would make the loop print the following output? To find the pattern, it can help to make a table. Each time count goes up by 1, the number should go up by 5. But count * 5 is too big by 3, so we must subtract number to print count * count * 5 - 3count 40

number to print ( y )‏ count (x)‏ 41

Caution: This is algebra, not assignment! Recall: slope-intercept form ( y = mx + b )‏ Slope is defined as “rise over run” (i.e. rise / run). Since the “run” is always 1 (we increment along x by 1), we just need to look at the “rise”. The rise is the difference between the y values. Thus, the slope ( m ) is the difference between y values; in this case, it is +5. To compute the y-intercept ( b ), plug in the value of y at x = 1 and solve for b. In this case, y = 2. y = m * x + b 2 = 5 * 1 + b Then b = -3 So the equation is y = m * x + b y = 5 * x – 3 y = 5 * count number to print ( y )‏ count (x)‏ 42

Algebraically, if we always take the value of y at x = 1, then we can solve for b as follows: y = m * x + b y 1 = m * 1 + b y 1 = m + b b = y 1 – m In other words, to get the y -intercept, just subtract the slope from the first y value ( b = 2 – 5 = -3 )‏ This gets us the equation y = m * x + b y = 5 * x – 3 y = 5 * count – 3 (which is exactly the equation from the previous slides)‏ 43

What statement could we write in the body of the loop that would make the loop print the following output? Let's create the loop table together. Each time count goes up 1, the number should... But this multiple is off by a margin of count * count * number to print count 44

45 Coding (different from execution check): n=keyboard.nextInt(); // try 6! for (int i = 1; i <= n; i++) { System.out.print("*"); } System.out.println(); Output: ****** 11/29/2015

46 More complicate case: n=keyboard.nextInt(); // try 6! for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { System.out.print("*"); } System.out.println(); } Output: ****** 11/29/2015

47 Code: n=keyboard.nextInt(); // try 5! for (int i = 1; i <= n; i++) { for (int j = 1; j <= 10; j++) { System.out.print( (i * j) + " "); } System.out.println(); } Output: /29/2015

How to confirm the initialization correct? On preparing the 1 st iteration … How to ensure the detail of the body? A consistent view of 1 st, 2 nd, 3 rd iterations … Map of the counter value to the iteration expression … 48

49 Code: n=keyboard.nextInt(); // try 6! for (i = 1; i<=n; i++) System.out.print(“*”); System.out.println(“”); for (i = 1; i <= n-2; i++) { System.out.print(“*”); for (int j = 1; j <= n-2; j++) System.out.print(“ ”); System.out.println(“*”); } for (i = 1; i<=n; i++) System.out.print(“*”); System.out.println(“”); Output: ****** * ****** 11/29/2015

50 Code: n=keyboard.nextInt(); // try 6! for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } Output: * ** *** **** ***** ****** 11/29/2015

51 Code: n=keyboard.nextInt(); // try 6! for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); } System.out.println(); } Output: /29/2015

52 Code: n=keyboard.nextInt(); // try 5! for (int i = 1; i <= n; i++) { for (int j = 1; j <= (n - i); j++) { System.out.print(" "); } for (int k = 1; k <= i; k++) { System.out.print(i); } System.out.println(); } Output: /29/2015

Otherwise (unknown or unclear), the loop is called a event-controlled loop. Use a while loop or a do-while loop for an easy checkpoint development. Asking the user before each iteration if it is time to end the loop is called the ask-before-iterating technique. Appropriate status update (or event initializing) for a sequence of iterations 11/29/ Controlling Event of Loop Iterations

11/29/201554

55 Finds and prints a number's first factor other than 1: int n = keyboard.nextInt(); // try 91 int f = 2; while (n % f != 0) { f++; } System.out.println("First factor:" + f); Sample run: First factor:7 11/29/2015

56 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 /29/2015

57 System.out.print("Type a non-negative integer: "); int n = keyboard.nextInt(); while (n < 0) { System.out.print("Invalid number, try again: "); n = keyboard.nextInt(); } int square = n * n; System.out.println(n + " squared is " + square); Notice that the number variable had to be declared outside the while loop in order to remain in scope. 11/29/2015

58 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 out 19 (i.e., ) Hint: Use the % operator to extract the last digit of a number. If we do this repeatedly, when should we stop? 11/29/2015

59 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); } } 11/29/2015

60 Write a program named CountFactors that reads in an integer and displays its number of factors. For example, if the user enters 60, CountFactors displays 12 because 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, and 60 are all factors of 60. Scanner keyboard = new Scanner(System.in); int n = keyboard.nextInt(); int sum = 0, k = ?; while ( ) { } System.out.println(“sum = “ + sum); 11/29/2015

Scanner keyboard =new Scanner(System.in); int n = keyboard.nextInt(); int k = 1; int sum = 0; while (k<=n) { if(n%k==0) sum ++; k++; } System.out.print("sum = " + sum); 61

Exercises (Wednesday lab) population TV purchase

63

64

Complete a Loop program 65

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 Random Number Generator 66

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 ( )‏ 67

Given the following declaration, how would you get: A random number between 0 and 100 inclusive? A random number between 1 and 100 inclusive? A random number between 4 and 17 inclusive? 68

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? int random1 = rand.nextInt(100) + 1; A random number between 4 and 17 inclusive? int random1 = rand.nextInt(14) + 4; 69

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! 70

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!"); } } 71

Fencepost Problem: Write a class named PrintNumbers that reads in an integer called max and prints each number from 1 to max, separated by commas. Example: java PrintNumbers Please enter a maximum integer: 5 should print: 1, 2, 3, 4, 5 72 Fencepost Problem

We want to print n numbers but need only n - 1 commas. Similar to the task of building a fence If we repeatedly place a post and wire, the last post has an extra dangling wire. A flawed algorithm: for (length of fence) { plant a post. attach some wire. } 73

import java.util.Scanner; public class PrintNumbers { public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); int max = keyboard.nextInt(); for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line } } Output when user enters 5: 1, 2, 3, 4, 5,// notice extra comma at end! unnecessary 74

import java.util.Scanner; public class PrintNumbers public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); int max = keyboard.nextInt(); for (int i = 1; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line } } Output when user enters 5:, 1, 2, 3, 4, 5// comma at beginning unnecessary 75

The solution is to add an extra statement outside the loop that places the initial "post." This is called a fencepost loop. The revised algorithm: plant a post. for (length of fence - 1) { attach some wire. plant a post. } 76

import java.util.Scanner; public class PrintNumbers public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); int max = keyboard.nextInt(); System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line } Output when user enters 5: 1, 2, 3, 4, 5// no extra comma! 77

WhileDemo.java, p202 DoWhileDemo.java, p206 ForDemo.java, p219 Exercises, slides 32, 45-52, 55-65, 70-71, 77 Summary 78

Test (controlling boolean expression, P201), body (P200), iteration (P200), and initialization (P228) While (P ), do-while (P204-9), and for loop (P ) Counter-controlled (P229) and event controlled loop Mapping iterations to counter values Trace and development template Random number generator The omission of {} and its side effect (P218) Extra semicolon (P222) and comma (P224) Invalidation and infinite loop (P213) The use of break and its function (P236-7) Scope of loop variable (P223) Fencepost problem and its solution 79