CSC153, Class 34: Loops ("Laaps" in Plan-Speak)
Overview:
* Review of Conditionals
* Reflection on Conditionals
* Overview of Loops
+ While Loops
+ Do Loops
+ For Loops
* Lab
Notes:
* Happy April Fools' Day.
* Exam 2 returned. Problem 3 not graded because it was wrong.
Whoops!
We may go over string->value at a later date.
* Read X3 (Input, Output, Files, and Exceptions); Focus on
Exceptions.
* Start homework 3 (A Raquetball Simulator).
We've looked at a variety of kinds of conditionals and
Boolean procedures
* Lots of kinds of "if"
How might we incorporate Booleans and conditionals in our
Rational class?
* Is object x a rational? A Builtin Java procedure,
instanceof
if (x instanceof Rational) ...
* Is the Rational equal to ...
+ Another Rational
+ Another object
* All the comparisons
int numerator;
int denominator;
public boolean lessThan(Rational other) {
return (this.numerator*other.denominator
< other.numerator*this.denominator)
} // lessThan(Rational)
(1) Convert to doubles and compare the doubles
+ Potential approximation
(2) If ad < cb then a/b < c/d
+ Potential overflow
* Back to equals
public boolean equals(Rational other) {
// Two rational numbers are equal if their reduced
// forms are the same.
return (this.reduce().numerator() == other.reduce().numerator())
&& (this.reduce().denominator() == other.reduce().denominator());
// Problem with above strategy: Reducing costs
// Alternate solution: Cross-multiply. Cheaper, but overflow
return (this.numerator*other.denominator
== other.numerator*this.denominator)
} // equals(Rational)
public boolean equals(Object other) {
return (other instanceof Rational) &&
(this.equals((Rational) other))
|| (other.instanceof Integer) && ...
}
----------------------------------------
On to Loops
Most languages provide at least three kinds of loops
* "Counting loop"
* "While loop":
Test
Holds -> Do "body" and go back to the test
Doesn't hold -> Exit loop
* "Repeat loop":
Do something
Test
Holds -> Go back to top
Otherwise -> Exit loop
for(intitialization; test; increment) {
body;
}
while (test) {
body
}
do {
body
} while (test);
The for loop is simply a shorthand for
initialization
while (test) {
body
increment
}
Do J5.1 and J5.3