Академический Документы
Профессиональный Документы
Культура Документы
Chapter 4
Spring 2007
CS 101
Aaron Bloomfield
Java looping
Options
while
do-while
for
Allow programs to control how many times a statement list is
executed
Averaging values
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
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
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
int valuesProcessed = 0;
double valueSum = 0;
// set up the input
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
} else {
System.out.println("No list to average");
}
Program Demo
NumberAverage.java
while
Expression
Action
10
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
Execution Trace
valuesProcessed
int valuesProcessed = 0;
double valueSum = 0;
0
1
2
3
valueSum
4.5
5.0
6.3
0
value
4.5
0.5
1.3
-1
average
2.1
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
}
else {
System.out.println("No list to average");
}
13
Light beer
Dandy lions
Assaulted
peanut
Eggplant
Dr. Pepper
Pool table
Tap dancers
Card shark
King of pop
I Pod
Gator aide
Knight mare
Hole milk
14
15
Sample run
An empty line
was entered
A Ctrl+z was
entered. tI is the
Windows escape
sequence for
indicating
end-of-file
17
Program Demo
LowerCaseDisplay.java
18
Program trace
public static void main(String[] args)
19
Program trace
20
21
22
Loop design
Questions to consider in loop design and analysis
What initialization
expression?
is
necessary
for
the
loops
test
Reading a file
Background
filename is a String
24
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
25
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();
}
Close
Determine
Set
Process
Display
Get
Make
up
first
next
sure
the
file
standard
current
lines
line
line
file
stream
got
fileone
stream
name
aline
input
line
by one
tostream
process
If not, loop is done
26
Todays demotivators
27
28
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 < 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
ForInit
ForExpr
true
Action
ForUpdate
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
( ForInit
; ForExpression
; ForUpdate
) Action
31
Variable declaration
You can declare a variable in any block:
while ( true ) {
int n = 0;
n++;
System.out.println (n);
}
System.out.println (n);
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
0
3
2
1
i is 0
i is 1
i is 2
all done
35
Translates to:
int count;
count = 0;
while (count < 10) {
System.out.println (count);
count++;
}
36
37
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);
}
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 < n; ++i) {
System.out.println("i is " + i);
for (int j = 0; j < i; ++j) {
System.out.println("
j is " + 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
0
0
1
0
1
2
40
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
41
From Dubai
42
do-while loops
43
Action
true
Expression
false
44
45
Guessing 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 );
46
Program Demo
GuessMyNumber.java
47
never executed
executed once
48
can
be
translated
into
while
do {
Action;
} while ( WhileExpression );
can be translated into:
boolean flag = true;
while ( WhileExpression || flag ) {
flag = false;
Action;
}
49
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
50
Todays demotivators
51
Loop controls
52
The continue keyword will immediately start the next iteration of the
loop
The rest of the current loop is not executed
But the ForUpdate part is, if continue is in a for loop
for ( int a = 0; a <= 10; a++ ) {
if ( a % 2 == 0 ) {
continue;
}
System.out.println (a + " is odd");
}
Output:
1
3
5
7
9
is
is
is
is
is
odd
odd
odd
odd
odd
53
The break keyword will immediately stop the execution of the loop
Execution resumes after the end of the loop
for ( int a = 0; a <= 10; a++ ) {
if ( a == 5 ) {
break;
}
System.out.println (a + " is less than five");
}
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
54
Four Hobos
55
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 NPRs Sunday Morning Edition puzzle person
56
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?
57
Analysis
We are looking for integer solutions to the formula:
a2+b2+c2+d2 = 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
58
Implementation
public class FourHobos {
public static void main (String[] args) {
for ( int a = 1; a <= 14; a++ ) {
for ( int b = 1; b <= 14; b++ ) {
for ( int c = 1; c <= 14; c++ ) {
for ( int d = 1; d <= 14; d++ ) {
if ( (a <= b) && (b <= c) && (c <= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println ("(" + a + ", " + b
+ ", " + c + ", " + d + ")");
}
}
}
}
}
}
}
}
59
Program Demo
FourHobos.java
60
Results
The output:
(2, 4, 6, 12)
(6, 6, 8, 8)
Not surprisingly, the smart hobo picks the short straw of the
first combination
61
Todays demotivators
62
Alternate implementation
We are going to rewrite the old code in the inner most for
loop:
if ( (a <= b) && (b <= c) && (c <= d) ) {
if ( a*a+b*b+c*c+d*d == 200 ) {
System.out.println ("(" + a + ", " + b
+ ", " + c + ", " + d + ")");
}
}
First, consider the negation of
( (a <= b) && (b <= c) && (c <= d) )
Its ( !(a <= b) || !(b <= c) || !(c <= d) )
Or ( (a > b) || (b > c) || (c > d) )
63
Alternate implementation
This is the new code for the inner-most for loop:
if ( (a > b) || (b > c)
continue;
}
if ( a*a+b*b+c*c+d*d !=
continue;
}
System.out.println ("("
+ c
|| (c > d) ) {
200 ) {
64
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
65
Ornithology
Nutrition
Peace
Acoustics
Mathematics
Literature
Medicine
Physics
Chemistry
Biology
3 card poker
67
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
68
Straight flush: both a flush and a straight
71
73
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
74
Program Demo
HandEvaluation.java
75
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
76
Flash animation
Reference: http://en.wikipedia.org/wiki/All_your_base_are_belong_to_us
77
78
80
81
A few notes
To solve the halting problem means we have a method
Oracle.CheckHalt (String P, String I)
Let Oracle be a class that can give lots of (truthful)
answers
Oracle.PredictFuture(),
Oracle.GetNextLotteryNumbers(), etc.
P is the (filename of the) program we are checking for
halting
I is the (filename of the) input to that program
And it will return loops forever or halts
As a boolean: true means loops forever, false means
halts
Note it must work for any (Java) program, not just some
programs
Or simple programs
82
o
nd
e
rs
ta
n
h.
.
N
t
u
on
Id
3.
2.
Yes
No
I dont understand
what the halting
problem is
Ye
1.
83
while (true)
...println (hello world);
System.exit();
o
nd
e
rs
ta
n
h.
.
N
t
u
on
Id
3.
2.
Yes
No
I dont understand
what the halting
problem is
Ye
1.
86
Perfect numbers
Numbers whose divisors (not including the number) add
up to the number
6=1+2+3
28 = 1 + 2 + 4 + 7 + 14
The list of the first 10 perfect numbers:
6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128,
2658455991569831744654692615953842176,
1915619426082361072947933780843036381309973215
48169216
The last one was 54 digits!
All known perfect numbers are even; its an open (i.e.
unsolved) problem if odd perfect numbers exist
Sequence A000396 in OEIS
87
88
o
nd
e
rs
ta
n
h.
.
N
t
u
on
Id
3.
2.
Yes
No
I dont understand
what the halting
problem is
Ye
1.
89
90
CheckHalt()s non-existence
Consider a program P with input I
Suppose that a method Oracle.CheckHalt(P,I) exists
Tests if P(I) will either loop forever or halt
A program is a series of bits
And thus can be considered data as well
Thus, we can call CheckHalt(P,P)
Its using the bytes of program P as the input to
program P
91
CheckHalt()s non-existence
Consider a new program:
public class Test {
public static void main (String args[]) {
if ( Oracle.CheckHalt(Test.java, Test.java) )
// if Test.java loops forever
System.exit();
// then halt
else
// else if Test.java halts
while (true) { }
// then loop forever
}
}
Do we agree that class Test is a valid program?
92
CheckHalt()s non-existence
A (somewhat condensed)
version of class Test:
Two possibilities:
if ( Oracle.CheckHalt
(Test.java,
Test.java) )
else
}
}
System.exit();
while (true) { }
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
94
95
96
97
Triangle counting
98
99
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
100
Program Demo
TriangleDemo.java
101
102
Steps required:
Check if the sides are in sorted order (i.e. x < y < 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 cant assume that once a property is present, the
103
others are not.
TriangleDemo.java
104
oo
. ..
so
oo
c.
..
I m
ll .
at
a
el
l.
N
ot
w
ot
N
da
ki
n
,b
u.
..
no
It
s
y.
ka
O
I m
t ..
a
it h
w
el
l
w
tg
re
at
l it
.. .
fi
st
uf
Th
is
i rl
y
Fa
5.
el
l!
4.
3.
ry
2.
1.
105
Fibonacci numbers
106
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
107
108
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?
109
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)
110
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
111
Reproducing rabbits
Note the sequence:
{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, }
The Fibonacci sequence again
112
Fibonacci sequence
Another application:
Fibonacci sequence
the
ratio
between
successive
terms
5 +1
F (n + 1)
= =
= 1.618933989
n F ( n)
2
lim
Reference: http://en.wikipedia.org/wiki/Golden_ratio
114
115
116
Number counting
117
118
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
119
120
121
Program Demo
NumberGames.java
122
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, its much slower than using ints and
longs
The Fibonacci number part didnt use BigIntegers
Thats why we got -980107325 for the 100th term
It flowed over the limit for ints called overflow
123
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 < n; i++ )
biggie = biggie.multiply (bigN);
System.out.println (biggie);
124
NumberGames.java
125