790 likes | 816 Views
Loop - CIS 1068 Program Design and Abstraction. Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen.jiang@temple.edu. Table of Contents. Taste of Loop While Loop Do While Loop For Loop Variations Controlling Number of Loop Iterations Loop Development
E N D
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen.jiang@temple.edu
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
Taste of Loop • Price is right. • Sample execution (click on this link to try) • Before you get the price right, the program will REPEAT…
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: <initialization>; while (<test>) { <body, consisting of statement(s)>; } Example: int number = 1; while (number <= 200) { System.out.print(number + " "); number *= 2; } Output: 1 2 4 8 16 32 64 128
The <initialization> prepares the variable declarations and their values that are used in the test, update, and body of the loop. The <test> checks whether the repetition of the loop body can stop. The statement or group of statements to be repeated is called the <body> of the loop. Each repetition of the loop body is called an <iteration> of the loop. Not clear?
<initialization>; while (<test>) { <body>; }
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
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: <initialization>; do { <statement(s)>; } while (<test>); Example: // roll until we get a number other than 3 Random rand = new Random(); int die; do { die = rand.nextInt(); } while (die == 3);
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.
for loop: A block of Java code that executes a group of statements repeatedly until a given test fails. General syntax: for (<initialization>; <test>; <update>) { <statement>; <statement>; ... <statement>; } Example: for (int i = 1; i <= 30; i++) { System.out.println("I will not throw..."); } Variant 2: for
for (<init>; <test>; <update>) { <body>; }
Summary Body first, and then event change/update
Initialization, test, and body, and execution results of loop • 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 1st iteration? 2nd iteration? 3rd iteration? …
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 -1 0 1 2 Example: for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) { System.out.println(i + " squared is " + (i * i)); }
The update can be a -- (or any other operator). Caution: This requires changing the test from <= to >= . 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!
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!");
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 This is printed 3 times This is printed 3 times So is this... or is it? Moral: Always use curly braces and always use proper indentation.
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; …
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!!!"); }
Loops that go on… forever while (true) { <statement(s)>; } If it goes on forever, how do you stop?
break statement: Immediately exits a loop (for, while, do/while). Example: while (true) { <statement(s)>; if (<test>) { break; } <statement(s)>; } Why is the break statement in an if statement?
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);
Special case: If a variable is declared in the <initialization> 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
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 }
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(); }
Exercises • http://www.cis.temple.edu/~jiang/1068LoopExecution.pdf
Loop Development population TV purchase 1+2+4+8+... 1+2+3+4+...+99 • http://www.cis.temple.edu/~jiang/LoopDevelopment.htm
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.
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 + " "); }
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 + " "); }
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. count number to print count * 5 count * 5 - 3 1 2 5 2 2 7 10 7 3 12 15 12 4 17 20 17 5 22 25 22
count (x) number to print (y) 1 2 2 7 3 12 4 17 5 22
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 count (x) number to print (y) 1 2 2 7 3 12 4 17 5 22
Algebraically, if we always take the value of y at x = 1, then we can solve for b as follows: y = m * x + b y1 = m * 1 + b y1 = m + b b = y1 – 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)
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 ... count number to print count * -4 count * -4 + 21 1 17 -4 17 2 13 -8 13 3 9 -12 9 4 5 -16 5 1 5 1 -20
Coding (different from execution check): n=keyboard.nextInt(); // try 6! for (int i = 1; i <= n; i++) { System.out.print("*"); } System.out.println(); Output: ****** What is the body? Counter-controlled loop?
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: ****** ****** ****** ****** ****** ****** What is the body? Counter-controlled loop?
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 What is the body? Counter-controlled loop? Initialization and body detail?
How to confirm the initialization correct? On preparing the 1st iteration … How to ensure the detail of the body? A consistent view of 1st, 2nd, 3rd iterations … Map of the counter value to the iteration expression …
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: ****** * * * * * * * * ****** What is the body? Counter controlled loop
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: * ** *** **** ***** ****** i * each line!