Week 8Week 5
COMP 111COMP 111
Introduction to Computer ScienceIntroduction to Computer Scienceand Object-Oriented Programmingand Object-Oriented Programming
Week 8
Feeling Out of the Loop?Feeling Out of the Loop?
Week 8
Methods - So Far Methods - So Far ……• Execute a sequence of statements
Declarations Assignment statements Return Maybe an output (e.g. System.out.println …)
• Execute in order First to last Until last is executed Or a return Or an error
• And from last week ….
With Expressions!
Week 8
Methods - So Far Methods - So Far ……• Optionally execute a sequence of statement• Alternatively execute
this sequence of statement or that sequence of statement
• With variations Series of comparisons Nested comparisons
With Conditons!
Week 8
But But ……
• While (as humans) we know how to Determine when an interest-bearing
investment reaches a target amount Do long division with remainders Average the scores of any 111 class on Test 1
• We cannot write methods that do these!(or at least not easily and in general!)
Week 8
They All Hinge on RepeatingThey All Hinge on Repeating
Describe how repetition drives … Determining when an interest-bearing
investment reaches a target amount Doing long division with remainders Averaging the scores of any 111 class
on Test 1
Week 8
Digging Deeper Digging Deeper ……
• In each case we repeat something gated by some critical test repeat something
• as long as• until
a test is true!
Week 8
They All Hinge on aThey All Hinge on a TestTest
Describe what key test drives … Determining when an interest-bearing
investment reaches a target amount Doing long division with remainders Averaging the scores of any 111 class
on Test 1
Week 8
Examples from the WorldExamples from the World• As long as the meat thermometer is less than
160 degrees, bake another 5 minutes• While the robot does not sense the wall ahead,
move it forward one unit
statementstatement
test false
truewhile a test is true statement
whatever is next
Week 8
Examples from the WorldExamples from the World• Keep going straight until you reach Putnam street• Continue adding stuff while the weight is less than 50 lbs
statementstatement
testfalse
true
do statementwhile a test is true
go on to next
Week 8
Examples from the WorldExamples from the World• Sum the usage minutes for
each day of the year• Compute 33! (33 factorial)
for (a range of counter values) statement
go on to nextstatementstatement
testcounter
false
true
initializecounter
adjustcounter
Week 8
The Java While LoopThe Java While Loop
• Want to repeat while something is true
statementstatement
test false
true
while (test){ statements}
Must the loop body be executed at least once?
the loopbody
Week 8
ConsiderConsider
• Compute integer division “the hard way” count how many times the divisor can be
subtracted from the dividend
dividenddivisorcount
1340
why stop?
A small “aha” fits this into an iteration framework?
Week 8
start the count at 0;while (the dividend >= than divisor){
subtract the divisor;increment the count;
}
Moving to the Moving to the ““WhileWhile””
• Compute integer division “the hard way” count how many times the divisor can be
subtracted from the dividenddividend
divisorcount
1340
542
941
143
Week 8
Realizing In JavaRealizing In Java
• Want to repeat while something is truepublic int divideBy(int num1, int num2){
int count = 0;int dividend = num1;
while (dividend >= num2){
dividend = dividend - num2;count++;
}return count;
}
Week 8
public int divideBy(int num1, int num2){
int count = 0;int dividend = num1;
while (dividend >= num2){
dividend = dividend - num2;count++;
}return count;
}
You Try It?You Try It?
Trace the value fordivideBy(20,5)
divideBy(3,5)
divideBy(7,7)
dividenddivisorcount 0
Week 8
public int divideBy(int num1, int num2){
int count = 0;int dividend = num1;
while (dividend >= num2){
dividend = dividend - num2;count++;
}return count;
}
The Gotcha!The Gotcha!
Trace the value fordivideBy(5,0)
divideBy(7,-2)
dividenddivisorcount 0
Week 8
public int divideBy(int num1, int num2){
int count = 0;int dividend = num1;
while (dividend > num2){
dividend = dividend - num2;count++;
}return count;
}
Another Gotcha!Another Gotcha!
Off-by-one errors!
dividenddivisorcount 0
Try divideBy(4,2)
BadTest
Week 8
The Java Do LoopThe Java Do Loop
statementstatement
testfalse
true
do{ statements}while (test);
• Always executes the body of the loop• At least once!
the loopbody
Week 8
ConsiderConsider
• Compute mystery math operationpublic int mystery(int m, int n){
int r;
do {
r = n % m;n = m;m = r;
} while (r != 0);
return n;}
mystery(8,20)
r n m 20 8
4 8 40 4 0
Week 8
ConsiderConsider
• Compute mystery math operationpublic int mystery(int m, int n){
int r;
do {
r = n % m;n = m;m = r;
} while (r != 0);
return n;}
mystery(20,8)
r n m 8 20
8 20 84 8 40 4 0
Week 8
ConsiderConsider
• Compute mystery math operationpublic int mystery(int m, int n){
int r;
do {
r = n % m;n = m;m = r;
} while (r != 0);
return n;}
mystery(3,11)
r n m 11 3
2 3 21 2 10 1 0
Week 8
What Is It?What Is It?
• Can you name the mystery operation mystery(20,8) = 4 mystery(8,20) = 4 mystery(3,11) = 1
Week 8
Another ProblemAnother Problem
What is the sum of thefirst n positive odd integers?
For example• the first 5 positive integers are 1, 3, 5, 7, 9• their sum is 25• easy, but what about sum of first 1000?
Week 8
A StrategyA Strategy What is the sum of the
first n positive odd integers?
• Start with odd number 1 with a sum of 0
• Repeat n times add the odd number to the sum find the next odd number
Week 8
Realizing the StrategyRealizing the Strategy What is the sum of the
first n positive odd integers?• Start
with odd number 1 with a sum of 0
• Repeat n times add the odd number to the sum find the next odd number
start the odd number at 1start the sum at 0;while (less than n times){ add the odd number to the sum; find next odd number;}
Week 8
Moving ForwardMoving Forward What is the sum of the
first n positive odd integers?• Start
with odd number 1 with a sum of 0
• Repeat n times add the odd number to the sum find the next odd number
int oddNum = 1;int sum = 0;
while (less than n times){ sum = sum + oddNum; oddNum = oddNum + 2;}
start the odd number at 1start the sum at 0;while (less than n times){ add the odd number to the sum; find next odd number;}
Week 8
Thinking About CountingThinking About Counting How do you count n times?
start a count at 0
while (count < n){ add 1 to the count;}
int count = 0;
while (count < n){ … count++;}
Note: when n is 5, this counts 0, 1, 2, 3, 4
How would you count 1, 2, 3, 4, 5?
Week 8
Putting It TogetherPutting It Together What is the sum of the
first n positive odd integers?
start the odd number at 1start the sum at 0;while (less than n times){ add the odd number to the sum; find next odd number;}
int count - 0;int oddNum = 1;int sum = 0;
while (count < n){ sum = sum + oddNum; oddNum = oddNum + 2; count++;}
int count = 0;
while (count < n){ … count++;}
Week 8
In a MethodIn a Methodpublic int sumFirstOdds(int n){
int count = 0;int oddNum = 1;int sum = 0;
while (count < n){ sum = sum + oddNum; oddNum = oddNum + 2; count++;}return sum;
}
sumFirstOdds(5)
n count oddNum sum
Week 8
You Try ItYou Try Itpublic int sumFirstOdds(int n){
int count = 0;int oddNum = 1;int sum = 0;
while (count < n){ sum = sum + oddNum; oddNum = oddNum + 2; count++;}return sum;
}
sumFirstOdds(1)
n count oddNum sum
Week 8
CountingCounting Is CommonIs Common
• Counting up, counting down, etc.• Using a counter (or index)
int count = 0;
while (count < n){ … count++;}
Week 8
The Java For LoopThe Java For Loop• Abbreviates the
initialization testing adjusting
of a counter• Implicitly executes them
for (init, testing, adjusting) statement statement
statement
testcounter
false
true
initializecounter
adjustcounter
implicit
implicit
implicit
Week 8
The Java The Java ForFor Loop Loop• Abbreviates the
initialization testing adjusting
of a counter
int count;for (count = 0; count < n; count++){ statements}
statementstatement
count< n
false
true
count = 0;
count++
implicit
implicit
implicit
Week 8
NotesNotes the the ForFor Loop Loop• Note the semicolons• Can declare counter within the for construct
for (int count = 0; count < n; count++){ statements}
Does the for replace the while loop?
Week 8
Using the Using the ForFor Loop Loop
public int sumFirstOdds(int n){
int oddNum = 1;int sum = 0;
for (count = 0; count < n; count++){ sum = sum + oddNum; oddNum = oddNum + 2;}return sum;
}
sumFirstOdds(5)
n count oddNum sum
Week 8
Would This Work?Would This Work?
public int sumFirstOdds(int n){
int oddNum = 1;int sum = 0;
for (count = 1; count <= n; count++){ sum = sum + oddNum; oddNum = oddNum + 2;}return sum;
}
sumFirstOdds(5)
n count oddNum sum