Conditionals and Loops
The goal of this assignment is to write five short Java programs
so that you get used to writing code and debugging it.
Do five of the following seven exercises.
All questions have equal weight.
Feel free to do more than five, but we will choose which ones
to grade if you submit more than the required amount.
- Distinct values.
Write a program Distinct.java
that takes three integer command line parameters a, b, and c and prints
out the number of distinct values (1, 2, or 3) among a, b, and c.
- What's your sign?
Write a program Zodiac.java that takes two command
line integers M and D and prints the Zodiac sign corresponding
to month M (1 = January, 12 = December) and day D. Use the
Write a program Checkerboard.java that
reads an integer, N from the command line, and prints out a two
dimensional N-by-N checkerboard pattern with
alternating spaces and asterisks, like the following 4-by-4 pattern.
* * * *
* * * *
* * * *
* * * *
Write a program Ordinals.java that takes a command line argument
N and prints out the first N ordinals, followed by Hello.
Hint: consider using (i % 10) and
(i % 100) to determine when to use "st", "nd",
"rd", or "th" for printing the ith Hello.
% java Ordinals 22
- Prime counting function.
counting function π(N) plays an important role in number theory.
It is defined to be the number of prime numbers less than or equal to N.
Write a program PrimeCounter.java that reads an integer
N from the command line and prints out π(N).
- Bohr radius.
Write a program BohrRadius.java
Newton's method to
find the radii where the probability of finding the electron in the
4s excited state of hydrogen is zero.
The probability is given by:
(1 - 3r/4 + r2/8 - r3/192)2 e-r/2,
where r is the radius in units of the Bohr radius.
Start Newton's method by reading a real number from the command line for the
initial value of r.
Hint: use the initial values r = 0, 5, and 13.
Challenge: explain what happens if you use an initial
value of r = 4, 10, and 12 (behavior may depend on your
- Center of mass.
Write a program CenterOfMass.java that reads in the position
and mass of n particles from standard input and prints out their
center of mass.
The input file consists of n lines
(although n is not known ahead of time), each containing
three real numbers representing the x coordinate, y
coordinate, and mass of the particle.
The center of mass of the n particles
(x1, y1, m1)
(xn, yn, mn)
is given by (x, y) where:
x = (m1x1 + ... + mnxn) / m
y = (m1y1 + ... + mnyn) / m
m = m1 + m2 + ... + mn