|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
We finished last lecture having walked through
/** Announce a countdown, starting at 10. * @return A countdown starting at 10. * That is, "10...9...8... [etc] 2...1...Liftoff!" */ public String countdown() { String chantSoFar = ""; /* A local variable, to accumulate the answer. */ int t = 10; /* The next number to count down. */ while (t >= 0) { chantSoFar = chantSoFar + (t + "..."); t = t-1; } return (chantSoFar + "Liftoff!"); } |
style tip: Don't just make the parameter named t and then assign to it (but mention that approach). Keeping the parameter untouched segues well into the next problem.
Challenge: Without changing the answer being computed, can you change how the answer is arrived at, by t counts from 1 up to (say) 10, and prepends that number to chant?
teaching comment: this was a useful exercise to do in class; or at least, it wasn't obvious to people!
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.
/** Return the nth triangular number. * @param n The number of rows in a triangle. * @return The number of pins needed to set up a n rows of pins, * each row containing one more pin than the previous. * That is, return 1+2+3+...+(n-1)+n. * Test cases: * triangularNumber(4) = 10 * triangularNumber(6) = 21 * ...other tests?... */ |
teaching note: Be sure to run a couple of live tests of this, to set up triangularPyramid, which will call this method.
Exercise Consider stacking oranges. This isn't two-dimensional like bowling pins sitting on the floor; oranges get stacked in pyramids. Every pyramid begins with a single orange at its peak, but there are several ways to extend the pyramid.
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Jan.24 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |