Title: Iteration
1Iteration
- Chapter 6
- Fall 2005
- CS 101
- Aaron Bloomfield
2Java looping
- Options
- while
- do-while
- for
- Allow programs to control how many times a
statement list is executed
3Averaging values
4Averaging
- 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
5Averaging
- 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
6Averaging
- 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
7- 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)
8- 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()
-
9Program Demo
10Todays dose of demotivators
11While syntax and semantics
Expression
Action
while
(
)
12While 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()
13While Semantics
Expression
false
true
Action
14Execution 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
15Converting text to lower case
16Converting 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 ""
-
- while (stdin.hasNext())
- String currentLine stdin.nextLine()
- String currentConversion
- currentLine.toLowerCase()
- converted (currentConversion "\n")
-
- System.out.println("\nConversion is\n"
- converted)
17Sample run
18Program Demo
19Program trace
public static void main(String args)
Scanner stdin new Scanner
(System.in) System.out.println("Enter input to
be converted") String converted
"" while (stdin.hasNext()) String
currentLine stdin.nextLine() String
currentConversion currentLine.toLowerCase()
converted (currentConversion
"\n") System.out.println("\nConversion
is\n" converted)
public static void main(String args)
Scanner stdin new Scanner
(System.in) System.out.println("Enter input to
be converted") String converted
"" while (stdin.hasNext()) String
currentLine stdin.nextLine() String
currentConversion currentLine.toLowerCase()
converted (currentConversion
"\n") System.out.println("\nConversion
is\n" converted)
20Program trace
converted (currentConversion "\n")
21Loop Design Reading From a File
22Loop 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?
23Reading a file
Scanner fileIn new Scanner (new File (filename)
)
24Reading 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
25Reading 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
26All your base are belong to us
- All your base history http//en.wikipedia.org/wik
i/All_your_base - Flash animation http//www.planettribes.com/allyo
urbase/AYB2.swf
27End of lecture on 5 October 2005
- Also went over
- Lab 6
- HW J4
- Mid semester review results
28The For statement
29The For Statement
currentTerm 1
int
for ( int i 0 i lt 5 i )
System.out.println(currentTerm)
currentTerm 2
30ForInit
ForExpr
true
false
Action
PostExpr
31for statement syntax
for
ForInit
ForExpression
ForUpdate
Action
(
)
32for 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
33Variable 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
34Variable 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
35Execution 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
36for 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
37for 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 (mostly) 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
38for 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 ) ...
39Nested 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
40Nested 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
41The 2005 Ig Nobel Prizes
- Agricultural history
- Physics
- Medicine
- Literature
- Peace
- Economics
- Chemistry
- Biology
- Nutrition
- Fluid dynamics
The Significance of Mr. Richard Buckleys
Exploding Trousers The pitch drop experiment,
started in 1927 Neuticles artificial
replacement testicles for dogs The 409 scams of
Nigeria for a cast of rich characters Locust
brain scans while they were watching Star
Wars For an alarm clock that runs away, thus
making people more productive Will Humans Swim
Faster or Slower in Syrup? For cataloging the
odors of 131 different stressed frogs To Dr.
Yoshiro Nakamats who catalogued and analyzed
every meal he ate for the last 34 years (and
counting) Pressures Produced When Penguins Pooh
Calculations on Avian Defaecation
42do-while loops
43The 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
44Picking 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
45Guessing a number
- This program will allow the user to guess the
number the computer has thought of - Main code block
- do
- System.out.print ("Enter your guess ")
- guessedNumber stdin.nextInt()
- count
- while ( guessedNumber ! theNumber )
46Program Demo
47while 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
48while 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 ( WhileExpression flag )
- flag false
- Action
49Hand Paintings
50Loop controls
51The continue keyword
- The continue keyword will immediately start the
next iteration of the loop - The rest of the current loop is not executed
- for ( int a 0 a lt 10 a )
- if ( a 2 0 )
- continue
-
- System.out.println (a " is odd")
-
- Output 1 is odd
- 3 is odd
- 5 is odd
- 7 is odd
- 9 is odd
52The break keyword
- The break keyword will immediately stop the
execution of the loop - Execution resumes after the end of the loop
- for ( int a 0 a lt 10 a )
- if ( a 5 )
- break
-
- System.out.println (a " is less than five")
-
- Output 0 is less than five
- 1 is less than five
- 2 is less than five
- 3 is less than five
- 4 is less than five
53Four Hobos
54Four Hobos
- An example of a program that uses nested for
loops - Credited to Will Shortz, crossword puzzle editor
of the New York Times - And NPRs Sunday Morning Edition puzzle person
- This problem is in section 6.10 of the text
55Problem
- Four hobos want to split up 200 hours of work
- The smart hobo suggests that they draw straws
with numbers on it - If a straw has the number 3, then they work for 3
hours on 3 days (a total of 9 hours) - The smart hobo manages to draw the shortest straw
- How many ways are there to split up such work?
- Which one did the smart hobo choose?
56Analysis
- We are looking for integer solutions to the
formula - a2b2c2d2 200
- Where a is the number of hours days the first
hobo worked, b for the second hobo, etc. - We know the following
- Each number must be at least 1
- No number can be greater than ??200 14
- That order doesnt matter
- The combination (1,2,1,2) is the same as
(2,1,2,1) - Both combinations have two short and two long
straws - We will implement this with nested for loops
57Implementation
- public class FourHobos
- public static void main (String args)
- for ( int a 1 a lt 14 a )
- for ( int b 1 b lt 14 b )
- for ( int c 1 c lt 14 c )
- for ( int d 1 d lt 14 d )
- if ( (a lt b) (b lt c) (c lt d) )
- if ( aabbccdd 200 )
- System.out.println ("(" a ", " b
- ", " c ", " d ")")
-
-
-
-
-
-
-
58Program Demo
59Results
- The output
- (2, 4, 6, 12)
- (6, 6, 8, 8)
- Not surprisingly, the smart hobo picks the short
straw of the first combination
60Alternate implementation
- We are going to rewrite the old code in the inner
most for loop - if ( (a lt b) (b lt c) (c lt d) )
- if ( aabbccdd 200 )
- System.out.println ("(" a ", " b
- ", " c ", " d ")")
-
-
- First, consider the negation of
- ( (a lt b) (b lt c) (c lt d) )
- Its ( !(a lt b) !(b lt c) !(c lt d) )
- Or ( (a gt b) (b gt c) (c gt d) )
61Alternate implementation
- This is the new code for the inner-most for loop
- if ( (a gt b) (b gt c) (c gt d) )
- continue
-
- if ( aabbccdd ! 200 )
- continue
-
- System.out.println ("(" a ", " b ", "
- c ", " d ")")
62Todays demotivators
63End of lecture on 10 October 2005
643 card poker
653 Card Poker
- This is the looping HW from last fall
- The problem count how many of each type of hand
in a 3 card poker game - Standard deck of 52 cards (no jokers)
- Four suits spades, clubs, diamonds, hearts
- 13 Faces Ace, 2 through 10, Jack, Queen, King
- Possible poker hands
- Pair two of the cards have the same face value
- Flush all the cards have the same suit
- Straight the face values of the cards are in
succession - Three of a kind all three cards have the same
face value - Straight flush both a flush and a straight
66The Card class
- A Card class was provided
- Represents a single card in the deck
- Constructor Card(int i)
- If i is in the inclusive interval 1 ... 52 then a
card is configured in the following manner - If 1 lt i lt 13 then the card is a club
- If 14 lt i lt 26 then the card is a diamond
- If 27 lt i lt 39 then the card is a heart
- If 40 lt i lt 52 then the card is a spade
- If i 13 is 1 then the card is an Ace
- If i 13 is 2, then the card is a 2, and so on.
67Card class methods
- String getFace()
- Returns the face of the card as a String
- String getSuit()
- Returns the suit of the card as a String
- int getValue()
- Returns the value of the card
- boolean equals(Object c)
- Returns whether c is a card that has the same
face and suit as the invoking card - String toString()
- Returns a text representation of the card. You
may find this method useful during debugging.
68The Hand class
- A Hand class was (partially) provided
- Represents the three cards the player is holding
- Constuctor Hand(Card c1, Card c2, Card c3)
- Takes those cards and puts them in sorted order
69Provided Hand methods
- public Card getLow()
- Gets the low card in the hand
- public Card getMiddle()
- Gets the middle card in the hand
- public Card getHigh()
- Gets the high card in the hand
- public String toString()
- Well see the use of the toString() method later
- public boolean isValid()
- Returns if the hand is a valid hand (no two cards
that are the same) - public boolean isNothing()
- Returns if the hand is not one of the winning
hands described before
70Hand Methods to Implement
- The assignment required the students to implement
the other methods of the Hand class - We havent seen this yet
- The methods returned true if the Hand contained a
winning combination of cards - public boolean isPair()
- public boolean isThree()
- public boolean isStraight()
- public boolean isFlush()
- public boolean isStraightFlush()
71Class HandEvaluation
- Required nested for loops to count the total
number of each hand - Note that the code for this part may not appear
on the website
72Program Demo
73Todays demotivators