Iteration - PowerPoint PPT Presentation

About This Presentation
Title:

Iteration

Description:

Quiz About [Your topic] - University of Virginia ... Iteration – PowerPoint PPT presentation

Number of Views:83
Avg rating:3.0/5.0
Slides: 58
Provided by: JimC94
Category:

less

Transcript and Presenter's Notes

Title: Iteration


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
  • Dont how big of a list to process
  • Need ability to repeat code as needed

4
Averaging
  • 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

5
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

6
  • public class NumberAverage
  • // main() application entry point
  • public static void main(String args)
  • // set up the input
  • // prompt user for values
  • // get first value
  • // process values one-by-one
  • while (value gt 0)
  • // add value to running total
  • // processed another value
  • // prepare next iteration - get next value
  • // display result
  • if (valuesProcessed gt 0)

7
  • int valuesProcessed 0
  • double valueSum 0
  • // set up the input
  • Scanner stdin new Scanner (System.in)
  • // prompt user for values
  • System.out.println("Enter positive numbers 1 per
    line.\n"
  • "Indicate end of the list with a negative
    number.")
  • // get first value
  • double value stdin.nextDouble()
  • // process values one-by-one
  • while (value gt 0)
  • valueSum value
  • valuesProcessed
  • value stdin.nextDouble()

notice the format!
8
While syntax and semantics
Expression

Action
while

(

)

9
While semantics for averaging problem
// process values one-by-one while ( value gt 0 )
// add value to running total valueSum
value // we processed another
value valueProcessed // prepare to iterate
get the next input value stdin.nextDouble()

10
While Semantics
Expression
false
true
Action
11
Execution Trace
Suppose input contains 4.5 0.5 1.3 -1
Suppose input contains 4.5 0.5 1.3 -1
Suppose input contains 4.5 0.5 1.3 -1
Suppose input contains 4.5 0.5 1.3 -1
Suppose input contains 4.5 0.5 1.3 -1
0
valuesProcessed
1
2
3
4.5
valueSum
0
5.0
6.3
int valuesProcessed 0 double valueSum
0 double value stdin.nextDouble() while
(value gt 0) valueSum value valuesProces
sed value stdin.nextDouble() if
(valuesProcessed gt 0) double average
valueSum / valuesProcessed System.out.println("A
verage " average) else System.out.println
("No list to average")
int valuesProcessed 0 double valueSum
0 double value stdin.nextDouble() while
(value gt 0) valueSum value valuesProces
sed value stdin.nextDouble() if
(valuesProcessed gt 0) double average
valueSum / valuesProcessed System.out.println("A
verage " average)
value
4.5
0.5
1.3
-1
average
2.1
12
Converting text to strictly lowercase
  • public static void main(String args)
  • Scanner stdin new Scanner (System.in)
  • System.out.println("Enter input to be
    converted")
  • String converted ""
  • String currentLine stdin.nextLine()
  • while (currentLine ! null)
  • String currentConversion
  • currentLine.toLowerCase()
  • converted (currentConversion "\n")
  • currentLine stdin.nextLine()
  • System.out.println("\nConversion is\n"
    converted)

13
Sample run
14
Program trace
public static void main(String args)
Scanner stdin new Scanner (System.in) Syst
em.out.println("Enter input to be
converted") String converted "" String
currentLine stdin.nextLine() while
(currentLine ! null) String
currentConversion currentLine.toLowerCase()
converted (currentConversion
"\n") currentLine stdin.nextLine() Syst
em.out.println("\nConversion is\n"
converted)
public static void main(String args)
Scanner stdin new Scanner (System.in) Syst
em.out.println("Enter input to be
converted") String converted "" String
currentLine stdin.nextLine() while
(currentLine ! null) String
currentConversion currentLine.toLowerCase()
converted (currentConversion
"\n") currentLine stdin.nextLine() Syst
em.out.println("\nConversion is\n"
converted)
15
Program trace
converted (currentConversion "\n")
16
Converting text to strictly lowercase
  • public static void main(String args)
  • Scanner stdin new Scanner (System.in)
  • System.out.println("Enter input to be
    converted")
  • String converted ""
  • String currentLine stdin.nextLine()
  • while (currentLine ! null)
  • String currentConversion
  • currentLine.toLowerCase()
  • converted (currentConversion "\n")
  • currentLine stdin.nextLine()
  • System.out.println("\nConversion is\n"
    converted)

17
All your base are belong to us
  • Flash animation
  • Reference http//en.wikipedia.org/wiki/All_your_b
    ase_are_belong_to_us

18
Loop design
  • Questions to consider in loop design and analysis
  • What initialization is necessary for the loops
    test expression?
  • What initialization is necessary for the loops
    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?

19
Reading a file
  • Background

Scanner fileIn new Scanner (new File (filename)
)
20
Reading a file
  • Class File
  • Allows access to files (etc.) on a hard drive
  • Constructor File (String s)
  • Opens the file with name s so that values can be
    extracted
  • Name can be either an absolute pathname or a
    pathname relative to the current working folder

21
Reading a file
  • Scanner stdin new Scanner (System.in)
  • System.out.print("Filename ")
  • String filename stdin.nextLine()
  • Scanner fileIn new Scanner (new File
    (filename))
  • String currentLine fileIn.nextLine()
  • while (currentLine ! null)
  • System.out.println(currentLine)
  • currentLine fileIn.nextLine()

Scanner stdin new Scanner (System.in) System.o
ut.print("Filename ") String filename
stdin.nextLine() Scanner fileIn new Scanner
(new File (filename)) String currentLine
fileIn.nextLine() while (currentLine ! null)
System.out.println(currentLine) currentLine
fileIn.nextLine()
Set up standard input stream
Determine file name
Set up file stream
Process lines one by one
Get first line
Make sure got a line to process
Display current line
Get next line
Make sure got a line to process If not, loop is
done
Close the file stream
22
The For Statement
currentTerm 1
int
for ( int i 0 i lt 5 i )
System.out.println(currentTerm)
currentTerm 2

23
ForInit
ForExpr
true
false
Action
PostExpr
24
for statement syntax
for
ForInit

ForExpression

ForUpdate

Action

(





)
25
for vs. while
  • A for statement is almost like a while statement
  • for ( ForInit ForExpression ForUpdate ) Action
  • is ALMOST the same as
  • ForInit
  • while ( ForExpression )
  • Action
  • ForUpdate
  • This is not an absolute equivalence!
  • Well see when they are different below

26
Variable declaration
  • You can declare a variable in any block
  • while ( true )
  • int n 0
  • n
  • System.out.println (n)
  • System.out.println (n)

Variable n gets created (and initialized) each
time
Thus, println() always prints out 1
Variable n is not defined once while loop ends
As n is not defined here, this causes an error
27
Variable declaration
  • You can declare a variable in any block
  • if ( true )
  • int n 0
  • n
  • System.out.println (n)
  • System.out.println (n)

Only difference from last slide
28
End of lecture on 1 November 2004
29
Execution Trace
i
0
1
2
3
  • System.out.println("i is " i)
  • System.out.println("all done")
  • System.out.println("i is " i)
  • System.out.println("all done")
  • i is 0
  • i is 1
  • i is 2
  • all done

int i 0
i lt 3
i
for (
)
int i 0
i lt 3
i
Variable i has gone out of scope it is local
to the loop
30
for vs. while
  • An example when a for loop can be directly
    translated into a while loop
  • int count
  • for ( count 0 count lt 10 count )
  • System.out.println (count)
  • Translates to
  • int count
  • count 0
  • while (count lt 10)
  • System.out.println (count)
  • count

31
for vs. while
  • An example when a for loop CANNOT be directly
    translated into a while loop
  • for ( int count 0 count lt 10 count )
  • System.out.println (count)
  • Would translate as
  • int count 0
  • while (count lt 10)
  • System.out.println (count)
  • count

only difference
count is NOT defined here
count IS defined here
32
for loop indexing
  • Java (and C and C) indexes everything from zero
  • Thus, a for loop like this
  • for ( int i 0 i lt 10 i ) ...
  • Will perform the action with i being value 0
    through 9, but not 10
  • To do a for loop from 1 to 10, it would look like
    this
  • for ( int i 1 i lt 10 i ) ...

33
Nested loops
  • int m 2
  • int n 3
  • for (int i 0 i lt n i)
  • System.out.println("i is " i)
  • for (int j 0 j lt m j)
  • System.out.println(" j is " j)
  • i is 0
  • j is 0
  • j is 1
  • i is 1
  • j is 0
  • j is 1
  • i is 2
  • j is 0
  • j is 1

34
Nested loops
  • int m 2
  • int n 4
  • for (int i 0 i lt n i)
  • System.out.println("i is " i)
  • for (int j 0 j lt i j)
  • System.out.println(" j is " j)
  • i is 0
  • i is 1
  • j is 0
  • i is 2
  • j is 0
  • j is 1
  • i is 3
  • j is 0
  • j is 1
  • j is 2

35
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

36
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
  • 1

37
while vs. do-while
  • If the condition is false
  • while will not execute the action
  • do-while will execute it once
  • while ( false )
  • System.out.println (foo)
  • do
  • System.out.println (foo)
  • while ( false )

never executed
executed once
38
while vs. do-while
  • A do-while statement can be translated into a
    while statement as follows
  • do
  • Action
  • while ( WhileExpression )
  • can be translated into
  • boolean flag true
  • while ( flag WhileExpression )
  • flag false
  • Action

39
End of lecture on 3 November 2004
  • We watched the Kerry concession speech and the
    Bush acceptance speech in class today, so after
    the announcements, we only got to about 20-25
    minutes of actual lecture time

40
A digression Perl again
  • Consider the statement
  • if ( !flag )
  • ...
  • else
  • ...
  • Perl has a command unless
  • unless ( flag )
  • ...
  • else
  • ...
  • An unless command is a if statement with a
    negated condition
  • It can get a bit confusing, though

41
A digression Perl again
  • Consider the statement
  • while ( !flag )
  • ...
  • Perl has a command until
  • until ( flag )
  • ...
  • An until command is a while loop with a negated
    condition
  • As most people are quite used to if-else and
    while, unless and until are rarely used

42
Problem solving
43
Data set manipulation
  • Often five values of particular interest
  • Minimum
  • Maximum
  • Mean
  • Standard deviation
  • Size of data set
  • Lets design a data set representation
  • The data set represents a series of numbers
  • Note that the numbers themselves are not
    remembered by the DataSet
  • Only properties of the set (average, minimum,
    etc.)

44
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

45
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

46
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 filep)
  • Initializes the data set using the values from
    the file represented by filep
  • Left to interested student

47
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 filep)
  • Adds the vales from the file represented by filep
    to the data set being represented
  • Left to interested student

48
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

49
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())
  • System.out.println()
  • dataset.clear()
  • dataset.load("stature.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()

50
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()
  • 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()

51
Example usage
52
Fractals
53
Methods getMinimum() and getMaximum()
  • Straightforward implementations given correct
    setting of instance variables
  • public double getMinimum()
  • return minimumValue
  • public double getMaximum()
  • return maximumValue

54
Method getSize()
  • Straightforward implementations given correct
    setting of instance variables
  • public int getSize()
  • return n

55
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

56
DataSet constructors
  • Straightforward using clear() and load()
  • public DataSet()
  • clear()
  • public DataSet(String s)
  • load(s)

57
Facilitator clear()
  • public void clear()
  • n 0
  • xSum 0
  • minimumValue Double.NaN
  • maximumValue Double.NaN

58
Facilitator add()
  • public void addValue(double x)
  • xSum x
  • n
  • if (n 1)
  • minimumValue maximumValue x
  • else if (x lt minimumValue)
  • minimumValue x
  • else if (x gt maximumValue)
  • maximumValue x

59
Facilitator load()
  • public void load(String s)
  • // get a reader for the file
  • Scanner fileIn new Scanner (new File(s))
  • // add values one by one
  • String currentLine fileIn.nextLine()
  • while (currentLine ! null)
  • double x Double.parseDouble(currentLine)
  • addValue(x)
  • currentLine fileIn.nextLine()
  • // close up file
Write a Comment
User Comments (0)
About PowerShow.com