Download presentation
Presentation is loading. Please wait.
Published byLouise Jackson Modified over 9 years ago
1
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen.jiang@temple.edu 1
2
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
3
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
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: 1 2 4 8 16 32 64 128 4
5
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
6
; while ( ) { ; } 6
7
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
8
Example, WhileDemo.java, P202, WhileDemo.java 8
9
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
10
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
11
Example, DoWhileDemo.java, P206, DoWhileDemo.java 11
12
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
13
for ( ; ; ) { ; } 13
14
Example, ForDemo.java, P219, ForDemo.java 14
15
Summary Body first, and then event change/update 15
16
16
17
17
18
18
19
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
20
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: -3 -2 0 1 2 Example: for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) { System.out.println(i + " squared is " + (i * i)); } 20
21
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 3 2 1 Blastoff! 21
22
What if we wanted the output to be the following? T-minus 3 2 1 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
23
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
24
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
25
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
26
Loops that go on… forever while (true) { ; } If it goes on forever, how do you stop? 26
27
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
28
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
29
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
30
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
31
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
32
3211/29/2015 Exercises http://www.cis.temple.edu/~jiang/1068LoopExecution.pdf
33
http://www.cis.temple.edu/~jiang/LoopDevelopment.htm Loop Development 33 population TV purchase 1+2+4+8+... 1+2+3+4+...+99
34
34
35
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
36
37
37
38
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? 0 2 4 6 8 … Answer: for (int count = 0; count < 49; count++) { System.out.print(2 * count + " "); } 38
39
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? 3 5 7 9 11 Answer: for (int count = 0; count < 49; count++) { System.out.print(2 * count + 3 + " "); } 39
40
What statement could we write in the body of the loop that would make the loop print the following output? 2 7 12 17 22 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 3. 1720174 22 12 7 2 number to print 25 15 10 5 count * 5 225 123 72 21 count * 5 - 3count 40
41
174 22 12 7 2 number to print ( y ) 5 3 2 1 count (x) 41
42
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 - 3 174 22 12 7 2 number to print ( y ) 5 3 2 1 count (x) 42
43
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
44
What statement could we write in the body of the loop that would make the loop print the following output? 17 13 9 5 1 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... 5-16 -20 -12 -8 -4 count * -4 1 9 13 17 count * -4 + 21 54 1 9 13 17 number to print 5 3 2 1 count 44
45
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
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
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: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 11/29/2015
48
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
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
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
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: 1 22 333 4444 55555 666666 11/29/2015
52
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: 1 22 333 4444 55555 11/29/2015
53
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/201553 Controlling Event of Loop Iterations
54
11/29/201554
55
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
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: 11 11 squared is 121 11/29/2015
57
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
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: 29107 prints out 19 (i.e., 2+9+1+0+7 ) 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
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
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
61
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
62
Exercises (Wednesday lab) population TV purchase 1+2+4+8+... 1+2+3+4+...+99 62
63
63
64
64
65
Complete a Loop program http://www.cis.temple.edu/~jiang/1068LoopComplete.pdf 65
66
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
67
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 ( - + 1 ) 67
68
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
69
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
70
Write a program that simulates the rolling of two six-sided dice until their combined result comes up as 7. 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! 70
71
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
72
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
73
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
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,// notice extra comma at end! unnecessary 74
75
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
76
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
77
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
78
WhileDemo.java, p202 DoWhileDemo.java, p206 ForDemo.java, p219 Exercises, slides 32, 45-52, 55-65, 70-71, 77 Summary 78
79
Test (controlling boolean expression, P201), body (P200), iteration (P200), and initialization (P228) While (P201-204), do-while (P204-9), and for loop (P217-221) 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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.