created 07/30/99
Instructions: Write each of these programs as specified. None of these programs ask the user to enter data. These programs have "hard coded" values where variables get their values through initialization or assignment statements. Usually this is a poor way to write a program. User input will be covered in the next two chapters. After you read them you could come back and write better versions of these programs.
Note: Each of these exercises asks you to run the program several times with different values for the variables. This is important to do! Playing with your programs is vital for understanding them and getting the feel of programming under you skin.
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.
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:
The output statement should be something like:
System.out.println("sine: " + sinx + " cosine: " + cosx + " sum of squares: " + sum );
Try a few other values besides 0.5236.
Click here to go back to the main menu.
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 Back to the main menu.
End of Exercises