created 07/30/99

Chapter 9 Programming Exercises

General Instructions: Write each of these programs as specified. None of these programs expect the user to enter data. The values one of these programs uses is "hard wired" into the program with declaration statements or assignment statements. Usually this is a poor way to write a program. Input will be covered in the next two chapters. After you read them you could come back and write a better version of these programs.

Note: Each of these exercises asks you to run the program several times with different values. This is important to do! Playing with your programs is vital to understanding them and getting "feel" of programming under you skin.

Exercise 1 --- Average Rain Fall

Write a program that averages the rain fall for three months, April, May, and June. Declare and initialize a variable to the rain fall for each month. Compute the average, and write out the results, something like:

Rainfall for April:  12
Rainfall for May  :  14
Rainfall for June:   8
Average rainfall:    11.333333
To get the numerical values to line up use the tabulation character '\t' as part of the character string in the output statements. Check that your program prints the correct results. There is a beginner's error lurking in this program too! Did you fall victim to it?

Click here to go back to the main menu.

Exercise 2 --- Trigonometry

To compute the sine of a double precision value use this method:

Math.sin( value )
The value is in radians (not degrees.) The cosine is computed using
Math.cos( value )
Again, value is in radians. Write a program that:
  1. Computes the sine of 0.5236 radians and saves it in a variable.
  2. Computes the cosine of 0.5236 radians and saves it in another variable.
  3. Computes the square of each those two values (use the variables), adds the two squares, and saves the result (in a third variable.)
  4. Writes out the three variables.
The output statement should be something like:
System.out.println("sine: " + sinx + " cosine: " + cosx + " sum: " + sum );
Try a few other values besides 0.5236.

Click here to go back to the main menu.

Exercise 3 --- Degrees to Radians

It is sometimes hard to think in terms of radians; we would rather use degrees. Remember (from those dark days of trigonometry class) that there are PI radians per 180 degrees. So to convert an angle given in degrees to radians do this:

rad = degrees * Math.PI/180
Math.PI gives you an accurate value of PI.

Edit the previous program so that it does the same things, but the angle is 30 degrees (which you will convert into radians.)

Click here to go back to the main menu.
End of Exercises