created 06/04/03

# Chapter 48 Programming Exercises

These exercises create a class, `Weight` that contains an array of the weight of an individual taken on successive days for one month.

## Exercise 1 ― Constructor and Print

Complete the constructor in the following program so that it constructs the array `data`, then copies values from the parameter array into `data`.

Then complete the `print()` method. If you want, write it so that it prints seven values per line, except for the last line.

```import java.io.* ;

class Weight
{
int[] data;

// Constructor
Weight(int[] init)
{
// Construct the array the same length
// as that referenced by init.
data = new ....

// Copy values from the
// input data to data.
for (int j.....)
{
data[j] =
}
}

//Print
void print()
{
for (int j.....)
{
System.out.println();
}
}

public static void main ( String[] args )
{
int[] values = { 98,  99,  98,  99, 100, 101, 102, 100, 104, 105,
105, 106, 105, 103, 104, 103, 105, 106, 107, 106,
105, 105, 104, 104, 103, 102, 102, 101, 100, 102};
Weight june = new Weight( values );
june.print();
}
}
```

## Exercise 2 ― Average

Now add an `average()` method to the class. Use integer math.

```import java.io.* ;

class Weight
{
. . .

int average()
{
. . .
}

public static void main ( String[] args )
{
int[] values = { 98,  99,  98,  99, 100, 101, 102, 100, 104, 105,
105, 106, 105, 103, 104, 103, 105, 106, 107, 106,
105, 105, 104, 104, 103, 102, 102, 101, 100, 102};
Weight june = new Weight( values );
int avg = june.average();
System.out.println("average = " + avg );
}
}
```

To check your method, initialize the array to ten values that have an easily computed average.

## Exercise 3 ― Subrange of Days

Now add another method that computes the average for a range of days. The method signature looks like this:

```int subAverage( int start, int end );
```

Make the range inclusive, that is, add up all days from `start` to and including `end`. You will probably get this wrong. Check your results, then debug your method.

In the `main()` method, use this method to compute the average of the first half of the month and then the second half of the month. Print out both averages and the difference between them. If the month has an odd number of days include the middle day in both averages.