|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Task 1: Stepping through a loop: What does mystery(4) return? Step through the code -- drawing the contents of each variable -- and find out!
int mystery (int n ) { int answerSoFar = 1; int i = 0; while (i < n) { answerSoFar = answerSoFar * 2; i = i + 1; } return answerSoFar } |
Self-challenge:
int fibber( int gens ) { int currGen = 0; int coneys = 0; int bunnies = 1; while ( currGen < gens ) { int updatedBunnies = adults; int updatedConeys = adults + bunnies; coneys = updatedConeys; bunnies = updatedBunnies; currGen = currGen + 1; } return coneys; } |
Task 2:
Let's revisit our
countdown code from last time,
but instead of building up our chantSoFar
as
"",
then "10...",
then "10...9...",
then "10...9...8..."
and so on,
let's build the same result the “other way 'round”:
"",
then "1...",
then "2...1...",
then "3...2...1...",
and so on.
The end result is exactly the same,
but as good programmers we should be able to
get to that result from either direction.
For next time...
Exercise In bowling, pins are arranged in a triangle with four layers; there are a total of 10 pins. You might be inspired on the weekends to make up your own bowling formats, lining up empty bottles of Grape Nehi, and realizing that you aren't confined to only four rows; you might have 5 rows (requiring 5 more empties, for a total of 15), or 6 rows (requiring yet 6 more empties, for a total of 21).
Of course, such home-grown bowling is only interesting for so long, and then you start wondering, in general, how many pins are needed for bowling-variants with other numbers of rows?
o ( 1 pin in a 1-high triangle) o o ( 3 pins in a 2-high triangle) o o o ( 6 pins in a 3-high triangle) o o o o (10 pins in a 4-high triangle) o o o o o etc. o o o o o oThat is, for a triangle with n rows, how many pins are needed? Write the method triangularNumber (or “tN”), which returns the nth triangular number
Before launching into the code, let's compute some examples/test-cases by hand, paying attention to our own thought process; that will give us a clue as to how to compute the general case.
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Apr.02 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |