# Iteration Chapter 6 Fall 2006 CS 101

```Iteration
Chapter 6
Fall 2006
CS 101
Aaron Bloomfield
1
Java looping
 Options
 while
 do-while
 for
 Allow programs to control how many times a statement list is
executed
2
Averaging values
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
 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)
// compute and display average
else
// indicate no average to display
}
}
int valuesProcessed = 0;
double valueSum = 0;
// set up the input
Scanner stdin = new Scanner (System.in);
// prompt user for values
System.out.println(&quot;Enter positive numbers 1 per line.\n&quot;
+ &quot;Indicate end of the list with a negative number.&quot;);
// get first value
double value = stdin.nextDouble();
// process values one-by-one
while (value &gt;= 0) {
valueSum += value;
++valuesProcessed;
value = stdin.nextDouble();
}
// display result
if (valuesProcessed &gt; 0) {
double average = valueSum / valuesProcessed;
System.out.println(&quot;Average: &quot; + average);
} else {
System.out.println(&quot;No list to average&quot;);
}
Program Demo

NumberAverage.java
9
While syntax and semantics
while
(
Expression
)
Action
Logical expression that
determines whether Action
is to be executed
Action is either a single
statement or a statement
list within braces
10
While semantics for averaging problem
Test expression is evaluated at the
start of each iteration of the loop.
// 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();
}
If test expression is true, these statements
are executed. Afterward, the test expression
is reevaluated and the process repeats
11
While Semantics
Expression is
evaluated at the
start of each
iteration of the
loop
Expression
If Expression is
true, Action is
executed
true
Action
false
If Expression is
false, program
execution
continues with
next statement
12
Suppose input contains: 4.5 0.5 1.3 -1
Execution Trace
valuesProcessed
int valuesProcessed = 0;
double valueSum = 0;
0
1
2
3
valueSum
4.5
6.3
5.0
0
value
0.5
1.3
4.5
-1
average
2.1
double value = stdin.nextDouble();
while (value &gt;= 0) {
valueSum += value;
++valuesProcessed;
value = stdin.nextDouble();
}
if (valuesProcessed &gt; 0) {
double average = valueSum / valuesProcessed;
System.out.println(&quot;Average: &quot; + average);
}
else {
System.out.println(&quot;No list to average&quot;);
}
13
New 2005 demotivatiors!
14
Converting text to lower case
16
Converting text to strictly lowercase
public static void main(String[] args)
{
Scanner stdin = new Scanner (System.in);
System.out.println(&quot;Enter input to be converted:&quot;);
String converted = &quot;&quot;;
while (stdin.hasNext()) {
String currentLine = stdin.nextLine();
String currentConversion =
currentLine.toLowerCase();
converted += (currentConversion + &quot;\n&quot;);
}
System.out.println(&quot;\nConversion is:\n&quot; +
converted);
}
17
Sample run
An empty line
was entered
A Ctrl+z was
entered. tI is the
Windows escape
sequence for
indicating
end-of-file
18
Program Demo

LowerCaseDisplay.java
19
Program trace
public static void main(String[] args)
{
Scanner stdin = new Scanner (System.in);
System.out.println(&quot;Enter input to be converted:&quot;);
String converted = &quot;&quot;;
while (stdin.hasNext()) {
String currentLine = stdin.nextLine();
String currentConversion =
currentLine.toLowerCase();
converted += (currentConversion + &quot;\n&quot;);
}
System.out.println(&quot;\nConversion is:\n&quot; +
converted);
20
Program trace
The append assignment operator updates the representation
of converted to include the current input line
converted += (currentConversion + &quot;\n&quot;);
Representation of lower case
conversion of current input line
Newline character is needed
because method nextLine()
&quot;strips&quot; them from the input
21
a File
22
Loop design
 Questions to consider in loop design and analysis
 What initialization
expression?
is
necessary
for
the
loop’s
test
 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?
23
 Background
Same Scanner class!
filename is a String
Scanner fileIn = new Scanner (new File (filename) );
It’s in the java.io package
24
 Class File
 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
25
Scanner stdin = new Scanner (System.in);
System.out.print(&quot;Filename: &quot;);
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();
}
Close
Determine
Set
Process
Display
Get
Make
up
first
next
sure
the
standard
file
current
lines
line
line
file
stream
got
fileone
stream
name
aline
input
line
by one
tostream
process
If not, loop is done
26
Today’s demotivators
27
The For statement
28
The For Statement
The body of the loop iterates
while the test expression is
true
Initialization step
is performed only
After each iteration of the
once -- just prior int currentTerm = 1;
body of the loop, the update
to the first
expression is reevaluated
evaluation of the for ( int i = 0; i &lt; 5; ++i ) {
test expression
System.out.println(currentTerm);
currentTerm *= 2;
The body of the loop displays the
}
current term in the number series.
It then determines what is to be the
new current number in the series
29
Evaluated once
at the beginning
of the for
statements's
execution
If ForExpr is true,
Action is
executed
After the Action
has completed,
the
PostExpression
is evaluated
ForInit
ForExpr
true
Action
PostExpr
After evaluating the
PostExpression, the next
iteration of the loop starts
The ForExpr is
evaluated at the
start of each
iteration of the
loop
false
If ForExpr is
false, program
execution
continues with
next statement
for statement syntax
Logical test expression that determines whether the action and update step are
executed
Initialization step prepares for the
first evaluation of the test
expression
for
( ForInit
; ForExpression
Update step is performed after
the execution of the loop body
; ForUpdate
) Action
The body of the loop iterates whenever
the test expression evaluates to true
31
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!
 We’ll see when they are different in a bit
32
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
33
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
34
Execution Trace
i
for ( int i = 0; i &lt; 3; ++i ) {
0
3
2
1
System.out.println(&quot;i is &quot; + i);
}
System.out.println(&quot;all done&quot;);
i is 0
i is 1
i is 2
all done
Variable i has gone
out of scope – it
is local to the loop
35
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++;
}
36
for vs. while
 An example when a for loop CANNOT be directly translated
into a while loop:
only difference
for ( int count = 0; count &lt; 10; count++ ) {
System.out.println (count);
}
count is NOT defined here
 Would (mostly) translate as:
int count = 0;
while (count &lt; 10) {
System.out.println (count);
count++;
}
count IS defined here
37
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++ ) { ... }
38
Nested loops
int m = 2;
int n = 3;
for (int i = 0; i &lt; n; ++i) {
System.out.println(&quot;i is &quot; + i);
for (int j = 0; j &lt; m; ++j) {
System.out.println(&quot;
j is &quot; + 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
39
Nested loops
int m = 2;
int n = 4;
for (int i = 0; i &lt; n; ++i) {
System.out.println(&quot;i is &quot; + i);
for (int j = 0; j &lt; i; ++j) {
System.out.println(&quot;
j is &quot; + j);
}
}
i is 0
i is 1
j is
i is 2
j is
j is
i is 3
j is
j is
j is
40
0
0
1
0
1
2
Another optical illusion
41
Loop controls
49
The 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 + &quot; is odd&quot;);
}

Output:
1
3
5
7
9
is
is
is
is
is
odd
odd
odd
odd
odd
50
The 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 + &quot; is less than five&quot;);
}

Output:
0
1
2
3
4
is
is
is
is
is
less
less
less
less
less
than
than
than
than
than
five
five
five
five
five
51
Today’s demotivators
52
Four Hobos
53
Four Hobos
 An example of a program that uses nested for loops
 Credited to Will Shortz, crossword puzzle editor of the New
York Times
 And NPR’s Sunday Morning Edition puzzle person
 This problem is in section 6.10 of the text
54
Problem
 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?
55
Analysis
 We are looking for integer solutions to the formula:
a2+b2+c2+d2 = 200
 Where a is the number of hours &amp; 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 doesn’t 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
56
Implementation
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) &amp;&amp; (b &lt;= c) &amp;&amp; (c &lt;= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println (&quot;(&quot; + a + &quot;, &quot; + b
+ &quot;, &quot; + c + &quot;, &quot; + d + &quot;)&quot;);
}
}
}
}
}
}
}
}
57
Program Demo

FourHobos.java
58
Results
 The output:
(2, 4, 6, 12)
(6, 6, 8, 8)
 Not surprisingly, the smart hobo picks the short straw of the
first combination
59
Alternate implementation
 We are going to rewrite the old code in the inner most for
loop:
if ( (a &lt;= b) &amp;&amp; (b &lt;= c) &amp;&amp; (c &lt;= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println (&quot;(&quot; + a + &quot;, &quot; + b
+ &quot;, &quot; + c + &quot;, &quot; + d + &quot;)&quot;);
}
}
 First, consider the negation of
( (a &lt;= b) &amp;&amp; (b &lt;= c) &amp;&amp; (c &lt;= d) )
 It’s ( !(a &lt;= b) || !(b &lt;= c) || !(c &lt;= d) )
 Or ( (a &gt; b) || (b &gt; c) || (c &gt; d) )
61
Alternate implementation
 This is the new code for the inner-most for loop:
if ( (a &gt; b) || (b &gt; c)
continue;
}
if ( a*a+b*b+c*c+d*d !=
continue;
}
System.out.println (&quot;(&quot;
+ c
|| (c &gt; d) ) {
200 ) {
+ a + &quot;, &quot; + b + &quot;, &quot;
+ &quot;, &quot; + d + &quot;)&quot;);
62
3 card poker
63
3 Card Poker
 This is the looping HW from a previous 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 3-card 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
64
 Straight flush: both a flush and a straight
The 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.
65
Card 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.
66
The 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
67
Provided 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()
 We’ll 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
68
Hand Methods to Implement
 The assignment required the students to implement the other
methods of the Hand class
 We haven’t 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()
69
Class 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
70
Program Demo

HandEvaluation.java
71
Becoming an IEEE author
72
Triangle counting
73
The programming assignment
 This was the looping HW from two springs ago
 List all the possible triangles from (1,1,1) to (n,n,n)
 Where n is an inputted number
 In particular, list their triangle type
 Types are: equilateral, isosceles, right, and scalene
74
Sample execution
Enter n: 5
(1,1,1)
(1,2,2)
(1,3,3)
(1,4,4)
(1,5,5)
(2,2,2)
(2,2,3)
(2,3,3)
(2,3,4)
(2,4,4)
(2,4,5)
isosceles equilateral
isosceles
isosceles
isosceles
isosceles
isosceles equilateral
isosceles
isosceles
scalene
isosceles
scalene
(2,5,5)
(3,3,3)
(3,3,4)
(3,3,5)
(3,4,4)
(3,4,5)
(3,5,5)
(4,4,4)
(4,4,5)
(4,5,5)
(5,5,5)
isosceles
isosceles equilateral
isosceles
isosceles
isosceles
right scalene
isosceles
isosceles equilateral
isosceles
isosceles
isosceles equilateral
75
Program Demo

TriangleDemo.java
76
The Triangle class
 That semester we went over classes by this homework
 So they had to finish the class
 We will be seeing class creation after spring break
 Methods in the class:
 public Triangle()
 public Triangle (int x, int y, int z)
 public boolean isTriangle()
 public boolean isRight()
 public boolean isIsosceles()
 public boolean isScalene()
 public boolean isEquilateral()
 public String toString()
77
The TriangleDemo class

Contained a main() method that tested all the triangles

Steps required:
 Check if the sides are in sorted order (i.e. x &lt; y &lt; z)
 If not, then no output should be provided for that collection
of side lengths
 Create a new Triangle object using the current side lengths
 Check if it is a valid triangle
 If it is not, then no output should be provided for that
collection of side lengths
 Otherwise, indicate which properties the triangle possesses
 Some side length values will correspond to more than 1
triangle
 e.g., (3, 3, 3) is both isosceles and equilateral
 Thus, we can’t assume that once a property is present, the
78
others are not.
Look at that them there code…

TriangleDemo.java
79
Today’s demotivators
80
End of this slide set?
81
Fibonacci numbers
82
Fibonacci sequence
 Sequences can be neither geometric or arithmetic
 Fn = Fn-1 + Fn-2, where the first two terms are 1
 Alternative, F(n) = F(n-1) + F(n-2)
 Each term is the sum of the previous two terms
 Sequence: { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … }
 This is the Fibonacci sequence
 Full formula:

1  5   1  5 
F ( n) 
n
5  2n
n
83
Fibonacci sequence in nature
13
8
5
3
2
1
84
Reproducing rabbits
 You have one pair of rabbits on an island
 The rabbits repeat the following:
 Get pregnant one month
 Give birth (to another pair) the next month
 This process repeats indefinitely (no deaths)
 Rabbits get pregnant the month they are born
 How many rabbits are there after 10 months?
85
Reproducing rabbits
 First month: 1 pair
 The original pair
 Second month: 1 pair
 The original (and now pregnant) pair
 Third month: 2 pairs
 The child pair (which is pregnant) and the parent pair
(recovering)
 Fourth month: 3 pairs
 “Grandchildren”: Children from the baby pair (now
pregnant)
 Child pair (recovering)
 Parent pair (pregnant)
 Fifth month: 5 pairs
 Both the grandchildren and the parents reproduced
 3 pairs are pregnant (child and the two new born rabbits)
86
Reproducing rabbits
 Sixth month: 8 pairs
 All 3 new rabbit pairs are pregnant, as well
pregnant in the last month (2)
 Seventh month: 13 pairs
 All 5 new rabbit pairs are pregnant, as well
pregnant in the last month (3)
 Eighth month: 21 pairs
 All 8 new rabbit pairs are pregnant, as well
pregnant in the last month (5)
 Ninth month: 34 pairs
 All 13 new rabbit pairs are pregnant, as well
pregnant in the last month (8)
 Tenth month: 55 pairs
 All 21 new rabbit pairs are pregnant, as well
pregnant in the last month (13)
as those not
as those not
as those not
as those not
as those not
87
Reproducing rabbits
 Note the sequence:
{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … }
 The Fibonacci sequence again
88
Fibonacci sequence
 Another application:

Fibonacci references from http://en.wikipedia.org/wiki/Fibonacci_sequence
89
Fibonacci sequence

As the terms increase,
approaches 1.618
the
ratio
between
successive
terms
F (n  1)
5 1
 
 1.618933989
n  F ( n)
2
lim

This is called the “golden ratio”
 Ratio of human leg length to arm length
 Ratio of successive layers in a conch shell

Reference: http://en.wikipedia.org/wiki/Golden_ratio
90
The Golden Ratio
91
92
Number counting
93
The programming assignment
 This was the looping HW from last fall
 Get an integer i from the user
 The homework had four parts
 Print all the Fibonacci numbers up to i
 Print all the powers of 2 up to i
 Print all the prime numbers up to i
 Time the previous three parts of the code
94
Sample execution
Input an integer i: 10
The 10th Fibonacci number is 55
Computation took 1 ms
2 3 5 7 11 13 17 19 23 29
The 10th prime is 29
Computation took 0 ms
The 10th power of 2 is 1024
Computation took 6 ms
2 4 8 16 32 64 128 256 512 1024
BigInteger: The 10th power of 2 is 1024
Computation took 2 ms
95
Background: Prime numbers
 Remember that a prime number is a number that is ONLY
divisible by itself and 1
 Note that 1 is not a prime number!
 Thus, 2 is the first prime number
 The first 10 prime numbers: 2 3 5 7 11 13 17 19 23 29
 The easiest way to determine prime numbers is with nested
loops
96
 Is actually pretty easy:
long start = System.currentTimeMillis();
// do the computation
long stop = System.currentTimeMillis();
long timeTakenMS = stop-start;
 This is in milliseconds, so to do the number of actual
seconds:
double timeTakenSec = timeTakenMS / 1000.0;
97
Program Demo

NumberGames.java

Note what happens when you enter 100


With the Fibonacci numbers
With the powers of 2
98
BigIntegers
 An int can only go up to 2^31 or about 2*109
 A long can only go up to 2^63, or about 9*1018
 What if we want to go higher?
 2100 = 1267650600228229401496703205376
 To do this, we can use the BigInteger class
 It can represent integers of any size
 This is called “arbitrary precision”
 Not surprisingly, it’s much slower than using ints and
longs
 The Fibonacci number part didn’t use BigIntegers
 That’s why we got -980107325 for the 100th term
 It “flowed over” the limit for ints – called “overflow”
99
BigInteger usage
 BigIntegers are in the java.math library
 import java.math.*;
 To get nn:
BigInteger bigN = new BigInteger (String.valueOf(n));
BigInteger biggie = new BigInteger (String.valueOf(1));
for ( int i = 0; i &lt; n; i++ )
biggie = biggie.multiply (bigN);
System.out.println (biggie);
100
Look at that them there code…

NumberGames.java
101
```