created 08/01/99


Chapter 11 Programming Exercises

Exercise 1

Write a program that calculates the annual cost of running an appliance. The program will ask the user for the cost per kilowatt-hour and the number of kilowatt-hours the appliance uses in a year:

Enter cost per kilowatt-hour  in cents
8.42
Enter kilowatt-hours used per year
653
Annual cost: 54.9826

Exercise 2

When a brick is dropped from a tower, it falls faster and faster until it hits the earth. The speed v is given by

v = (1/2) g t2

Here v is the speed in feet per second, t is the time in seconds, and g is 32.174. Write a program that asks the user for the number of seconds and then prints out the speed.

Enter the number of seconds
5.4
Speed of the brick: 469.092 feet per second

One hundred miles per hour is 146.67 feet per second. Use your program to determine approximately how long it takes the brick to reach that speed.


Exercise 3

The base 2 logarithm of a number is defined by:

log2 X = n  if 2n = X

For example

log2 32 = 5,  because  25 = 32  
log2 1024 = 10,  because 210 = 1024 

Write a program that inputs a number and outputs its base 2 logarithm. Use floating point input. This problem would be easy, but the Math package does not have a base 2 logarithm method. Instead you have to do this:

log2 X = (loge X) / (loge 2)

Here, loge X is the natural logarithm of X. Use this function in the Java Math package:

Math.log( X )

When you use this, X must be a double. Write the program so that the user can enter floating point numbers.

Enter a double:
998.65
Base 2 log of 998.65 is 9.963835330516641

Exercise 4

The harmonic mean of two numbers is given by:

H = 2 / ( 1/X + 1/Y )

This is sometimes more useful than the more usual average of two numbers. Write a program that inputs two numbers (as floating point) and writes out both the usual average (the arithmetic mean) and the harmonic mean.

Enter X:
12
Enter Y:
16
Arithmetic mean: 14.0
Harmonic   mean: 13.714285714285715