CSC 141 Computer Science I Zhen Jiang Dept
- Slides: 64
CSC 141 Computer Science I Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 zjiang@wcupa. edu 12/12/2021 1
Loop n n Smart if-decision making, smart program work, talent programmer Research experience (REU) - click on this link n n n Temperature/humidity detection every second A repetition process for the 7 x 24 hours seamless surveillance Needs a computer support to REPEAT … 12/12/2021 2
n While loop n n 12/12/2021 Format & Logic, page 193, Figure 4 -1. Sample, code 4 -3, page 194. 3
<initialization>; while (<test>) { <body>; } 12/12/2021 4
n Do-while loop n n n 12/12/2021 Format, page 204 Logic, page 205, Figure 4 -6. Sample, code 4 -6, page 205. 5
n 12/12/2021 How does this differ from the while loop? n The controlled <statement(s)> will always execute the first time, regardless of whether the <test> is true or false. 6
n For loop n n n 12/12/2021 Format, page 208, Figure 4 -7. Logic, page 208, Figure 4 -8. Sample, code 4 -7, page 209. 7
for (<init>; <test>; <update>) { <body>; } 12/12/2021 8
n Summary Body first, and then event change/update 12/12/2021 9
n n 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 2 3 4 squared is is 1 4 9 16 10
Variations n The initial and final values for the loop counter/event variable can be arbitrary expressions: n Example: for (int i = -3; i <= 2; i++) { System. out. println(i); } Output: -3 -2 -1 0 1 2 n Example: for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) { System. out. println(i + " squared is " + (i * i)); } 11
n The update can be a -- (or any other operator). n 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! 12
n What if we wanted the output to be the following? T-minus 3 2 1 Blastoff! n System. out. 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!"); 13
n When controlling a single statement, the {} braces are optional. for (int i = 1; i <= 6; i++) System. out. println(i + " squared is " + (i * i)); n 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? n Moral: Always use curly braces and always use proper indentation. 14
n Extra semicolon in a loop (P 218). int i; for (i = 1; i <= 6; i++); System. out. println(i + " squared is " + (i * i)); Output: 7 squared is 49 n Comman in a loop (P 220). int sum; for (int i=0, sum; … int i, sum; for (i = 1, sum = 0; i <= 10; i++) sum = sum + i * i; System. out. println("Result is " + sum); Output: 385 15
n Invalidation: Loops that never execute. for (int i = 10; i < 5; i++) { System. out. println("How many times do I print? "); } n ERROR: Loop tests that never fail. n A loop that never terminates is called an infinite loop. for (int i = 10; i >= 1; i++) { System. out. println("Runaway Java program!!!"); } 16
n Loops that go on… forever while (true) { <statement(s)>; } n If it goes on forever, how do you stop? 17
n n break statement: Immediately exits a loop (for, while, do/while). Example: while (true) { <statement(s)>; if (<test>) { break; } <statement(s)>; } n Why is the break statement in an if statement? 18
n 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 input. Number = console. next. Int(); if (input. Number == -1) { // don't add -1 to sum break; } sum += input. Number; // input. Number != -1 here } System. out. println("The total was " + sum); 19
n 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’s scope x's scope } // i no longer exists here } // x ceases to exist here 20
n 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 } 21
n COMMON ERROR: Using the wrong loop counter variable. n n n 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(); } 22
n Ex 10 n n http: //www. cs. wcupa. edu/~zjiang/141_ex 10. pdf Ex 11 n 12/12/2021 http: //www. cs. wcupa. edu/~zjiang/141_ex 11. pdf 23
n Trial n population n n TV purchase n n http: //www. cs. wcupa. edu/~zjiang/tv 563. exe 1+2+4+8+. . . n n http: //www. cs. wcupa. edu/~zjiang/6 billion. exe http: //www. cs. wcupa. edu/~zjiang/1_2_4. exe 1+2+3+4+. . . +99 n 12/12/2021 http: //www. cs. wcupa. edu/~zjiang/1 to 99. exe 24
n Development process n 12/12/2021 http: //www. cis. temple. edu/~jiang/Loop. Development. htm 25
12/12/2021 26
Controlling Number of Loop Iterations n If the number of iterations is known before the loop starts, the loop is called a count- controlled loop. n n n 12/12/2021 Counter =0, counter++, counter <number Counter = 1, counter++, counter <=number Use for loop for an easy development. 27
12/12/2021 28
12/12/2021 29
Mapping iterations to counter values n n n 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 + " "); } 30
n n n 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 + " "); } 31
n 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 n To find the pattern, it can help to make a table. n n 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 - 3 1 2 5 2 2 7 10 7 3 12 15 12 4 17 20 17 5 22 25 22 32
count (x) number to print (y) 1 2 2 7 3 12 4 17 5 22 33
n n 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 n 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 34
n 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 n In other words, to get the y-intercept, just subtract the slope from the first y value (b = 2 – 5 = -3) n 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) 35
n 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 n Let's create the loop table together. n n Each time count goes up 1, the number should. . . But this multiple is off by a margin of. . . count number to print count * -4 + 21 1 17 -4 17 2 13 -8 13 3 9 -12 9 4 5 -16 5 5 1 -20 1 36
n Code: for (int i = 1; i <= 4; i++) { System. out. println(i + " squared is " + (i * i)); } Output: 1 2 3 4 squared is is 1 4 9 16 http: //www. cs. wcupa. edu/~zjiang/141_ex 11. pdf 12/12/2021 37
n Coding (different from execution check): n=keyboard. next. Int(); // try 6! for (int i = 1; i <= n; i++) { System. out. print("*"); } System. out. println(); Output: ****** 12/12/2021 38
n More complicate case: n=keyboard. next. Int(); // try 6! for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { System. out. print("*"); } System. out. println(); } Output: ****** ****** 12/12/2021 39
n Code: n=keyboard. next. Int(); // 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 4 6 8 10 12 14 16 18 20 6 9 12 15 18 21 24 27 30 8 12 16 20 24 28 32 36 40 10 15 20 25 30 35 40 45 50 12/12/2021 40
n n 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 … 41
n Code: n=keyboard. next. Int(); // 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: ****** * ****** 12/12/2021 42
n Code: n=keyboard. next. Int(); // try 6! for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System. out. print("*"); } System. out. println(); } Output: * ** ****** 12/12/2021 43
n Code: n=keyboard. next. Int(); // 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 12/12/2021 44
n Code: n=keyboard. next. Int(); // 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 12/12/2021 45
Controlling Event of Loop Iterations n Otherwise (unknown or unclear), the loop is called a event-controlled loop. n n 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. n 12/12/2021 Appropriate status update (or event initializing) for a sequence of iterations 46
12/12/2021 47
n Finds and prints a number's first factor other than 1: int n = keyboard. next. Int(); // try 91 int f = 2; while (n % f != 0) { f++; } System. out. println("First factor: " + f); Sample run: First factor: 7 12/12/2021 48
n 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 11 squared is 121 12/12/2021 again: -1 -235 -87 11 49
System. out. print("Type a non-negative integer: "); int n = keyboard. next. Int(); while (n < 0) { System. out. print("Invalid number, try again: "); n = keyboard. next. Int(); } int square = n * n; System. out. println(n + " squared is " + square); n Notice that the number variable had to be declared outside the while loop in order to remain in scope. 12/12/2021 50
n Write a class named Digit. Sum 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 ) n Hint: Use the % operator to extract the last digit of a number. If we do this repeatedly, when should we stop? 12/12/2021 51
import java. util. Scanner; public class Digit. Sum { public static void main(String [] args) { Scanner keyboard = new Scanner(System. in); int n = keyboard. next. Int(); 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); } } 12/12/2021 52
n Write a program named Count. Factors that reads in an integer and displays its number of factors. n For example, if the user enters 60, Count. Factors 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. next. Int(); int sum = 0, k = ? ; while ( ) { } System. out. println(“sum = “ + sum); 12/12/2021 53
Scanner keyboard =new Scanner(System. in); int n = keyboard. next. Int(); int k = 1; int sum = 0; while (k<=n) { if(n%k==0) sum ++; k++; } System. out. print("sum = " + sum); 54
n Exercise n population n n TV purchase n n http: //www. cis. temple. edu/~jiang/tv 563. exe 1+2+4+8+. . . n n http: //www. cis. temple. edu/~jiang/6 billion. exe http: //www. cis. temple. edu/~jiang/1_2_4. exe 1+2+3+4+. . . +99 n http: //www. cis. temple. edu/~jiang/1 to 99. exe 12/12/2021 55
12/12/2021 56
Solution 12/12/2021 57
n Ex 12 n n http: //www. cs. wcupa. edu/~zjiang/141_ex 12. pdf Ex 13 n 12/12/2021 http: //www. cs. wcupa. edu/~zjiang/141_ex 13. pdf 58
n File writing, page 230 -237 n n n 12/12/2021 Filename Pring. Writer Println Close Sample, code 4 -17, page 233 59
n Appending data to a (existing) file n 12/12/2021 File. Writer (, true), page 236 60
n File Reading, page 237 -241 n n n 12/12/2021 File Scanner next. XXXX( ) close Sample, code 4 -18, page 238. 61
n Detecting the end of a file n n n has. Next Code 4 -19, page 241. Detecting the existence of a file n n 12/12/2021 exists Code 4 -21, page 245. 62
n Random number generator n n 12/12/2021 random. Numbers. next. XXX( ) Sample, code 4 -23, page 250. 63
n Objects of the Random class generate pseudo-random numbers. n n Class Random is found in the java. util package. import java. util. *; The methods of a Random object Method name next. Int() next. Int(max) Description returns a random integer in the range [0, max) in other words, from 0 to one less than max next. Double() returns a random real number in the range [0. 0, 1. 0) 12/12/2021 64
- Zhen jiang actor
- Zhen gu
- Zhen dong berkeley
- Cis 1068
- Zhen._.nnnn
- Favorite subject is science
- Feifei jiang
- Zhe jiang
- Dr shan jiang
- Set of closely grouped islands
- Tianxiao jiang
- Roland jiang
- Roland jiang
- Qiang jiang
- Qiang jiang
- Priehrada tri rokliny
- Xun jiang
- Raymond jiang
- "jiepu jiang"
- Hornboch
- Jiang jeishi
- Zheng jiang history
- Guomindang ap world history
- Rbac 140
- 141.ir
- Cse 141
- Cse 141
- Code checker
- Pt 141 nasal spray reviews
- Art 141 cod fiscal
- Upn 141
- Fas 141 real estate
- How many months is 141 days
- Ee 141
- D-141
- Chemistry 141
- Fasb 142
- Art 141 lgt
- Ieee 141
- Ee 141
- 134/141
- Cse 141
- Ley 141 15
- Integrity service excellence
- Ap-141
- Dept nmr spectroscopy
- Florida department of agriculture and consumer services
- Organizational structure of finance department
- Worcester building dept
- Dept. name of organization (of affiliation)
- Mn dept of education
- Department of finance and administration
- Dept. name of organization
- Employment first ohio
- Dept. name of organization (of affiliation)
- Vaginal dept
- Gome dept
- Gome dept
- Nyttofunktion
- Gome dept
- Hoe dept
- Lafd interview questions
- Maine department of agriculture conservation and forestry
- Dept of education
- Florida dept of agriculture and consumer services