Java Reference

In-Depth Information

Printing Pascal's triangle

Activity 9-4.1 of the CD gives a procedure for printing the first
n
rows of

Pascal's triangle. The major difficulty is in formatting it nicely. Each row should

be centered around the vertical axis, which means that row
0
, which has only one

value, has to be preceded by a number of blanks that depends on how many char-

acters the last row takes.

Further, there are two ways to print the triangle: (1) each integer value takes

only the number of characters that it needs and (2) all integers are printed using

the number of characters required by the largest integer.

Please see the CD for a full discussion of printing Pascal's triangle.

Get the method

from a footnote

on lesson page

9-4.

9.4

Key concepts

• Array types
.
type
[][]
is the type of a two-dimensional array with base type

type
,
type
[][][]
is the type of a three-dimensional array, etc. Elements of a two-

dimensional array
b
are referenced using
b[r][c]
, elements of a three-dimen-

sional array using
b[r][c][d]
, etc.

• Rectangular array
. A rectangular array can be created using the new-expres-

sion
type
[nrow][ncols]
.

• Row-major and column-major order
. Processing an array in row-major order

means processing the elements in row 0, then the elements in row 1, and so on.

Processing in column-major order means processing the elements in column 0,

then the elements in column 1, etc.

• Ragged array
. In Java, multi-dimensional arrays are really arrays of arrays (of

arrays, etc.). Expression
new
type
[5][][]
creates a one-dimensional array object

with
5
elements, all set to
null
; each of the
5
elements has type
type
[][]
, so it

can hold the name of an object that is a one-dimensional array of elements of

type
type
[]
. If the five elements are arrays of different lengths, the array is called

a
ragged array
.

Exercises for Chapter 9

E1.
A teacher is having trouble remembering the names of her 15 students, so she

arranges the desks into a rectangle with 5 rows and 3 columns. The names of her

students are: John, Jill, Pete, Chris, Mary, Seth, Gary, Teresa, Hanna, Amanda,

Kim, Greg, George, Perry, and Mike. Write Java code to store the names of the

students in a
5x3
two-dimensional array of
String
s.

E2.
The teacher (see exercise E1) has memorized her students' names and wants

to give them new seats. Write a method to randomly shuffle the array.

E3.
At the Water Hill stables, the horse stalls are arranged in a rectangle, 6 stalls

by 5 stalls. Create a boolean array that will indicate which horses have been fed.

Search WWH ::

Custom Search