created 08/01/99; edited 06/09/2015


Chapter 13 Programming Exercises

Exercise 1 — Annual Appliance Cost

Write a program that calculates the annual cost of running an appliance. The program asks 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

Click here to go back to the main menu.


Exercise 2 — Distance a Brick Travels

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

d = (1/2)gt2

Here d is in feet, 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 distance traveled.

Enter the number of seconds: 5.4
Distance: 469.096

Use the program to determine how far a brick falls in 100 seconds.

Click here to go back to the main menu.


Exercise 3 — Logarithm Base Two

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, which you can compute using

Math.log( X )

As usual, X is a double. The user enters floating point numbers:

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

Click here to go back to the main menu.


Exercise 4 — Harmonic Mean

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

Click here to go back to the main menu.