RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lect11a
and yet more with `while`

When writing a while-loop, keep these things in mind:

We'll apply these steps to the following problem(s).

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 o
That 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?...
 */
When computing this myself, I find that I am keeping track of two pieces of information: the total number of pins needed so far, and which row-number I'm currently working on. (There is also the parameter n, given to me.)
teaching note: Be sure to run a couple of live tests of this, to set up triangularPyramid, which will call this method.

Solution;

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.


If we finish these examples, we will talk about:

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Apr.06 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme