CSC141 Computer Science I Zhen Jiang Dept. of Computer Science

Slides:



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

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.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Java Programming: From the Ground Up
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 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,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
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.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
Adapted from slides by Marty Stepp and Stuart Reges
Categories of loops definite loop: Executes a known number of times.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Loop Structures.
Topic 5 for Loops -Arthur Schopenhauer
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
CSC 142 Computer Science II
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Chapter 4 Control structures and Loops
CSC240 Computer Science III
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSc 110, Spring 2017 Lecture 4: Nested Loops and Loop Figures
Building Java Programs
Control Statements Loops.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSC115 Introduction to Computer Programming
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
The for loop suggested reading:
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Suggested self-checks:
Building Java Programs
Control Statements Loops.
Repetition Statements
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Indefinite loop variations
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
Presentation transcript:

CSC141 Computer Science I Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 zjiang@wcupa.edu 6/11/2018

Loop Smart if-decision making, smart program work, talent programmer Research experience (REU) - click on this link Temperature/humidity detection every second A repetition process for the 7x24 hours seamless surveillance Needs a computer support to REPEAT … 6/11/2018

While loop Format & Logic, page 193, Figure 4-1. Sample, code 4-3, page 194. 6/11/2018

<initialization>; while (<test>) { <body>; } 6/11/2018

Do-while loop Format, page 204 Logic, page 205, Figure 4-6. Sample, code 4-6, page 205. 6/11/2018

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. 6/11/2018

For loop Format, page 208, Figure 4-7. Logic, page 208, Figure 4-8. Sample, code 4-7, page 209. 6/11/2018

for (<init>; <test>; <update>) { <body>; } 6/11/2018

Summary Body first, and then event change/update 6/11/2018

1st iteration? 2nd iteration? 3rd iteration? … 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 1 2 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 So is this... or is it? Moral: Always use curly braces and always use proper indentation.

int sum; for (int i=0, sum; … Extra semicolon in a loop (P218). 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); 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; } 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(); for (int j = 1; j <= 5; i++) {

Ex10 Ex11 http://www.cs.wcupa.edu/~zjiang/141_ex10.pdf http://www.cs.wcupa.edu/~zjiang/141_ex11.pdf 6/11/2018

Trial population TV purchase 1+2+4+8+... 1+2+3+4+...+99 http://www.cs.wcupa.edu/~zjiang/6billion.exe TV purchase http://www.cs.wcupa.edu/~zjiang/tv563.exe 1+2+4+8+... http://www.cs.wcupa.edu/~zjiang/1_2_4.exe 1+2+3+4+...+99 http://www.cs.wcupa.edu/~zjiang/1to99.exe 6/11/2018

Development process http://www.cis.temple.edu/~jiang/LoopDevelopment.htm 6/11/2018

6/11/2018

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. 6/11/2018

6/11/2018

6/11/2018

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

17 4 22 12 7 2 number to print (y)‏ 5 3 1 count (x)‏

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 = 5 * x – 3 y = 5 * count - 3 17 4 22 12 7 2 number to print (y)‏ 5 3 1 count (x)‏

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 = 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 ... 5 4 1 9 13 17 number to print 3 2 count 5 -16 -20 -12 -8 -4 count * -4 1 9 13 17 count * -4 + 21

1st iteration? 2nd iteration? 3rd iteration? … 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? … http://www.cs.wcupa.edu/~zjiang/141_ex11.pdf 6/11/2018

Counter-controlled loop? 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? 6/11/2018

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? 6/11/2018

Counter-controlled loop? Initialization and body detail? 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? 6/11/2018

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 …

Counter controlled loop 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(“*”); } Output: ****** * * What is the body? Counter controlled loop 6/11/2018

i * each line! Code: Output: 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! 6/11/2018

How many numbers each line? What are they? 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 How many numbers each line? What are they? 6/11/2018

Space and numbers? 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 Space and numbers? 6/11/2018

Controlling Event of Loop Iterations 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 6/11/2018

6/11/2018

Body: exploring the factor. When/what to stop the loop? 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 Body: exploring the factor. When/what to stop the loop? n% f = = 0 divisible! The range of f? Initialization of f? The change of f? 6/11/2018

Type a non-negative integer: -5 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 6/11/2018

Body: trying different value of n. When/what to stop the loop? n>= 0 non-negative! The range of n? -> any (since n<0) Initialization of n? The change of n? 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. 6/11/2018

Enter a nonnegative number: 29107 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? 6/11/2018

When/what to stop? All digits are counted! Body: adding the last digit and extracting that from the original number (for next round) When/what to stop? All digits are counted! n <= 0 no more need to count! The change of n? -> make the extraction valid Initialization? 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); 6/11/2018

When/what to stop? K>n (trial from 1 is over) Body: try all possible numbers k, count k (sum++) only when n is divisible by k. When/what to stop? K>n (trial from 1 is over) The range of k? -> 1 to n Change? k++ Initialization? 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); 6/11/2018

Scanner keyboard =new Scanner(System. in); int n = keyboard 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);

Exercise population TV purchase 1+2+4+8+... 1+2+3+4+...+99 http://www.cis.temple.edu/~jiang/6billion.exe TV purchase http://www.cis.temple.edu/~jiang/tv563.exe 1+2+4+8+... http://www.cis.temple.edu/~jiang/1_2_4.exe 1+2+3+4+...+99 http://www.cis.temple.edu/~jiang/1to99.exe 6/11/2018

6/11/2018

Solution 6/11/2018

Ex 12 Ex 13 http://www.cs.wcupa.edu/~zjiang/141_ex12.pdf http://www.cs.wcupa.edu/~zjiang/141_ex13.pdf 6/11/2018

File writing, page 230-237 Filename PringWriter Println Close Sample, code 4-17, page 233 6/11/2018

Appending data to a (existing) file FileWriter (, true), page 236 6/11/2018

File Reading, page 237-241 File Scanner nextXXXX( ) close Sample, code 4-18, page 238. 6/11/2018

Detecting the end of a file hasNext Code 4-19, page 241. Detecting the existence of a file exists Code 4-21, page 245. 6/11/2018

Random number generator randomNumbers.nextXXX( ) Sample, code 4-23, page 250. 6/11/2018

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()‏ Description Method name 6/11/2018