Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 CSC141 Computer Science I 12/11/20151.

Slides:



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

Loops (Part 1) Computer Science Erwin High School Fall 2014.
Computer Science 1620 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:
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
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.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
LAB 10.
1 for Loops Computer Science is a science of abstraction - creating the right model for a problem and devising the appropriate mechanizable techniques.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. 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
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
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.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
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.*;
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.
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.
Copyright 2010 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 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:
Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson All rights reserved.
Nested for loops.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
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.
Adapted from slides by Marty Stepp and Stuart Reges
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Chapter 5: Control Structures II
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
TK1114 Computer Programming
Something about Java Introduction to Problem Solving and Programming 1.
CSC 142 Computer Science II
CSC240 Computer Science III
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Loop Development Zhen Jiang Dept. of Computer Science
Building Java Programs
CSC115 Introduction to Computer Programming
CSc 110, Spring 2017 Lecture 4: Nested Loops and Loop Figures
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
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
Presentation transcript:

Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151

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

While loop Format & Logic, page 197, Figure 4-1. Sample, code 4-3, page /11/20153

4 ; while ( ) { ; }

Do-while loop Format, page 208 Logic, page 209, Figure 4-6. Sample, code 4-6, page /11/20155

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

For loop Format, page 212, Figure 4-7. Logic, page 212, Figure 4-8. Sample, code 4-7, page /11/20157

8 for ( ; ; ) { ; } 12/11/2015

9 Summary Body first, and then event change/update

Ex10 Ex /11/201510

Trial population TV purchase /11/201511

Development process 12/11/201512

12/11/201513

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. 12/11/201514

12/11/201515

12/11/201516

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 + " "); } 17

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

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 19

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

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)‏ 21

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)‏ 22

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 23

24 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 12/11/2015

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

26 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: ****** 12/11/2015

27 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: /11/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 … 28

29 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: ****** * ****** 12/11/2015

30 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: * ** *** **** ***** ****** 12/11/2015

31 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: /11/2015

32 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: /11/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 12/11/ Controlling Event of Loop Iterations

12/11/201534

35 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 12/11/2015

36 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 /11/2015

37 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. 12/11/2015

38 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? 12/11/2015

39 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); } } 12/11/2015

40 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); 12/11/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); 41

Exercise population TV purchase /11/201542

12/11/201543

Solution 12/11/201544

Ex 12 Ex /11/201545

File writing, page Filename PringWriter Println Close Sample, code 4-17, page /11/201546

Appending data to a (existing) file FileWriter (, true), page /11/201547

File Reading, page File Scanner nextXXXX( ) close Sample, code 4-18, page /11/201548

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

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

51 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 12/11/2015