Download presentation
Presentation is loading. Please wait.
1
Iteration
2
Java looping Options while do-while for
Allow programs to control how many times a statement list is executed
3
Averaging Problem Extract a list of positive numbers from standard input and produce their average Numbers are one per line A negative number acts as a sentinel to indicate that there are no more numbers to process Observations Cannot supply sufficient code using just assignments and conditional constructs to solve the problem Don’t how big of a list to process Need ability to repeat code as needed
4
Averaging Problem Extract a list of positive numbers from standard input and produce their average Numbers are one per line A negative number acts as a sentinel to indicate that there are no more numbers to process Algorithm Prepare for processing Get first input While there is an input to process do { Process current input Get the next input } Perform final processing NumberAverage.java
5
While syntax and semantics
When a while statement is executed, its test expression is evaluated first. If the expression evaluates true, its body is executed, where the body is the action of the while statement. The evaluation process then is repeated. If the expression reevaluates to true, the body is executed again. This process is called looping, and it continues until the test expression evaluates to false. At that point, execution continues with the next statement in the program.
6
While semantics for averaging problem
When a while statement is executed, its test expression is evaluated first. If the expression evaluates true, its body is executed, where the body is the action of the while statement. The evaluation process then is repeated. If the expression reevaluates to true, the body is executed again. This process is called looping, and it continues until the test expression evaluates to false. At that point, execution continues with the next statement in the program.
7
Averaging Problem Extract a list of positive numbers from standard input and produce their average Numbers are one per line A negative number acts as a sentinel to indicate that there are no more numbers to process Sample run Enter positive numbers one per line. Indicate end of list with a negative number. 4.5 0.5 1.3 -1 Average 2.1
8
While Semantics
9
Execution Trace Suppose input contains: 4.5 0.5 -1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); The tracing of the execution of a method by hand is an important program debugging technique. Hand-checking code can give insight into how a method works. Service.java
10
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); The tracing of the execution of a method by hand is an important program debugging technique. Hand-checking code can give insight into how a method works.
11
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum
12
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum value 4.5
13
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum value 4.5
14
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 4.5 value 4.5
15
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 4.5 value 4.5
16
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 4.5 value 0.5 4.5
17
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 4.5 value 0.5
18
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 4.5 5.0 value 0.5
19
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 2 1
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value 0.5
20
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 2
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value -1 1.3
21
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 2
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value -1
22
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 2
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value -1
23
Execution Trace Suppose input contains: 4.5 0.5 -1 valuesProcessed 2
int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value -1 average 2.5
24
Execution Trace Suppose input contains: 4.5 0.5 1.3 -1 valuesProcessed
2 int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble()); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble()); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); else { System.out.println("No list to average"); valueSum 5.0 value -1 average 2.5
25
Loop design Questions to consider in loop design and analysis
What initialization is necessary for the loop’s test expression? What initialization is necessary for the loop’s processing? What causes the loop to terminate? What actions should the loop perform? What actions are necessary to prepare for the next iteration of the loop? What conditions are true and what conditions are false when the loop is terminated? When the loop completes what actions are need to prepare for subsequent program processing?
26
Sentinel For some input data sets there is no reasonable sentinel value Examples Process a series of arbitrary numbers Processing lines of arbitrary text What can we do? Use Scanner methods and an operating system sentinel hasNext() hasNextInt() ... We will only use hasNext() MSDOS sentinel Unix sentinel MAC sentinel CTRL-Z CTRL-D ?
27
Reading a file Background
28
Reading a file Class File
Provides a system-independent way of representing a file name Constructor File(String s) Creates a File with name s Name can be either an absolute pathname or a pathname relative to the current working folder
29
Echoing a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close();
30
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Set up standard input stream
31
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Determine file name
32
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Determine the associated file
33
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Set up file stream
34
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Process lines one by one
35
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Is there any text
36
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Get the next line of text
37
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Display current line
38
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Make sure there is another to process If not, loop is done
39
Reading a file Scanner stdin = new Scanner(System.in);
System.out.print("Filename: "); String filename = stdin.next(); File file = new File(filename); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine); } fileIn.close(); Close the stream
40
The For Statement
41
The For Statement
42
The For Statement
43
The For Statement
44
The For Statement
46
For statement syntax
47
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i
48
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i
49
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i
50
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println(“i is " + i); } System.out.println(“all done"); i is 0 i
51
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i 1
52
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i 1
53
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i 1
54
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i 1
55
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i 2
56
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i 2
57
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 i 2
58
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 i 2
59
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 i 3
60
Execution Trace for (int i = 0; i < 3; ++i) {
System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 i 3
61
Variable i has gone out of scope – it
Execution Trace for (int i = 0; i < 3; ++i) { System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 all done 3 i is undefined – its scope is limited to the loop Variable i has gone out of scope – it is local to the loop
62
Nested loops int m = 2; int n = 3; for (int i = 0; i < n; ++i) {
System.out.println("i is " + i); for (int j = 0; j < m; ++j) { System.out.println(" j is " + j); } is part of the action associated with the for loop that begins on the third line of the segment. We say that this loop is the outer loop. The expression i < n that controls the iteration of the loop evaluates to true three times with i taking on in turn the values 0, 1, and 2. Thus, there are three lines of output that begin with “i is ”. Each time there is such a display, the for loop beginning on the fifth line of the segment is executed. We say this loop is an inner or nested loop. It is important to realize that an inner loop starts up once per iteration of its outer loop. For our example, each time the inner loop is executed, the expression j < m evaluates to true two times with j taking on in turn the values 0 and 1. Nesting one loop in another loop produces a multiplicative effect in terms of the number of statements that are executed. For our example, the outer for loop action is executed n times. Each one of those times, the inner for loop action is executed m times. As a result, the inner for loop action is performed a total of m n times.
63
What’s the output Counting.java int counter1 = 0; int counter2 = 0;
for (int i = 0; i < 5; ++i) { ++counter1; for (int j = 0; j < 10; ++j) { ++counter2; for (int k = 0; k < 2; ++k) { ++counter3; } ++counter4; ++counter5; System.out.println(counter1 + " " + counter2 + " " + counter3 + " " + counter4 + " " + counter5);
64
What’s the output Implement a program that displays the first n numbers in the Fibonacci sequence, where n is a user-specified integer value The sequence starts with the following numbers: 1, 1, 2, 3, 5, 8, 13, 21 After the initial two 1s, each number in the sequence is the sum of the two previous numbers. For example, = 2, = 3, = 5, = 8, and so on Fibonacci.java
65
The do-while statement
Syntax do Action while (Expression) Semantics Execute Action If Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action true Expression false
66
Picking off digits Consider
System.out.print("Enter a positive number: "); int number = stdin.nextInt()); do { int digit = number % 10; System.out.println(digit); number = number / 10; } while (number != 0); Sample behavior Enter a positive number: 1129 9 2 1 There is always at least one digit to display. A segment with a while loop would be either awkward or have repeated code
67
Problem solving
68
Internet per 100 people for 189 entities
69
Data set manipulation Often five values of particular interest Minimum
Maximum Mean Standard deviation Size of data set Let’s design a data set representation Together the minimum and maximum let us know the range of the values; the mean is the average data set value, which often gives insight on what is a typical value; and the standard deviation gives insight on how clustered the data set values are around the average. (Our implementation of a data set representation DataSet.java leaves the computing of a standard deviation to the exercises.)
70
What facilitators are needed?
71
Implication on facilitators
public double getMinimum() Returns the minimum value in the data set. If the data set is empty, then Double.NaN is returned, where Double.NaN is the Java double value representing the status not-a-number public double getMaximum() Returns the maximum value in the data set. If the data set is empty, then Double.NaN is returned
72
Implication on facilitators
public double getAverage() Returns the average value in the data set. If the data set is empty, then Double.NaN is returned public double getStandardDeviation() Returns the standard deviation value of the data set. If the data set is empty, then Double.NaN is returned Left to the interested student public int getSize() Returns the number of values in the data set being represented
73
What constructors are needed?
74
Constructors public DataSet()
Initializes a representation of an empty data set public DataSet(String s) Initializes the data set using the values from the file with name s public DataSet(File file) Initializes the data set using the values from the file Left to interested student
75
Other methods public void addValue(double x)
Adds the value x to the data set being represented public void clear() Sets the representation to that of an empty data set public void load(String s) Adds the vales from the file with name s to the data set being represented public void load(File file) Adds the vales from the file to the data set being represented Left to interested student
76
What instance variables are needed?
77
Instance variables private int n
Number of values in the data set being represented private double minimumValue Minimum value in the data set being represented private double maximumValue Maximum value in the data set being represented private double xSum The sum of values in the data set being represented
78
Example usage DataSet dataset = new DataSet("age.txt");
System.out.println(); System.out.println("Minimum: " + dataset.getMinimum()); System.out.println("Maximum: " + dataset.getMaximum()); System.out.println("Mean: " + dataset.getAverage()); System.out.println("Size: " + dataset.getSize()); dataset.clear(); dataset.load("stature.txt");
79
Example usage dataset.load("foot-length.txt");
System.out.println("Minimum: " + dataset.getMinimum()); System.out.println("Maximum: " + dataset.getMaximum()); System.out.println("Mean: " + dataset.getAverage()); System.out.println("Size: " + dataset.getSize()); System.out.println(); dataset.clear();
80
Example usage
81
Methods getMinimum() and getMaximum()
Straightforward implementations given correct setting of instance variables public double getMinimum() { return minimumValue; } public double getMaximum() { return maximumValue;
82
Method getSize() Straightforward implementations given correct setting of instance variables public int getSize() { return n; }
83
Method getAverage() Need to take into account that data set might be empty public double getAverage() { if (n == 0) { return Double.NaN; } else { return xSum / n;
84
DataSet constructors Straightforward using clear() and load()
public DataSet() { clear(); } public DataSet(String s) throws IOException { load(s);
85
Facilitator clear() public void clear() { n = 0; xSum = 0;
minimumValue = Double.NaN; maximumValue = Double.NaN; }
86
Facilitator add() public void addValue(double x) { xSum += x; ++n;
if (n == 1) { minimumValue = maximumValue = x; } else if (x < minimumValue) { minimumValue = x; else if (x > maximumValue) { maximumValue = x;
87
Facilitator load() public void load(String s) throws IOException {
// get a reader for the file Scanner fileIn = Scanner.create( new File(s) ); // add values one by one while (fileIn.hasNext()) { double x = fileIn.nextDouble); addValue(x); } // close up file fileIn.close();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.