created 07/30/99; revised 04/24/00

# Chapter 9 Programming Exercises

General Instructions: Write each of these programs as specified. These programs uses values that are "hard wired" into the program with declaration statements or assignment statements. Better versions of these programs would ask the user to enter values. In a few chapters you will learn how to do that.

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

## Exercise 1 — Payroll Program

Examine this program (from the chapter):

```class Example
{
public static void main ( String[] args )
{
long   hoursWorked = 40;
double payRate     = 10.0, taxRate = 0.10;
System.out.println("Hours Worked: " + hoursWorked );
System.out.println("pay Amount  : " + (hoursWorked * payRate) );
System.out.println("tax Amount  : " + (hoursWorked * payRate * taxRate) );
}
}
```

Modify it so that each variable is declared by itself and is not initialized. Next write three assignment statements to assign a value to each variable. Run the program; examine the output.

Now let's break something: Remove one of the declarations from the program. Can you compile it?

Now remove one of the initializations from the correct program. (For example, delete the characters "= 40" from the first declaration. Try to compile and run the program. When is a problem detected?

Say that you are interested in the value of the quadratic

3X2 -8X + 4

for several values of X. Write a program that has a double precision variable X. Assign a value to it. Write statement that computes a value for the quadradic and stores the result in another double precision variable. Finally write out the result, something like:

```At X = 4.0 the value is 20.0
```

Run the program with several values for X (edit the program for each value of X) and examine the result. Use values with decimal points, large values, small values, negative values, and zero. Solve the equation with paper and pencil (use the quadradic formula.) The quadradic should evaluate to zero at X = 2.0 and at X = 2/3. Try these values for X. Are the results exactly correct?

## Exercise 3 — Reassigning values to Variables

Modify the program in exercise 2 so that one run of the program will evaluate and write out the value of the quadradic for three different values of X: 0.0, 2.0, and 4.0 (or any three values of your choice.)

Write the program using only two variables, probably called x and value. Of course this means that you will have to put different things in these variables in different places in the program.

In writing the program make use of your editor's "copy" and "paste" functions to avoid re-typing similar lines.