Motivation

In this lesson, we look at a simple problem where the solution needs a Java array.

Scenario: Calculating deviations from an average

Imagine a grade-school class during an arithmetic lesson. The teacher has planned an exercise using a calculator. She will announce ten numbers, and each student is to find the numbers’ sum. After that, she has some other calculations planned.

The twins, Vandee and Vander—Dee and Der to their friends—are anxious to show off their skills. As the teacher announces each of the ten numbers, the students key each one into their calculators. Dee likes to keep track of everything, so she carefully writes the number in her notebook before keying it into her calculator. Der, on the other hand, immediately enters it into his calculator without writing it down.

Both Dee and Der get the right answer. The teacher now asks them to divide their sum by 10 to get the average of the numbers she has given them. Again, Dee and Der calculate this value correctly. The teacher discusses the concept of average, using familiar examples, such as the average height of all the students in the room:

“Are you taller or shorter than average?” she asks. “If you subtract the average height from your height, the difference will be positive, zero, or negative. This result indicates, respectively, whether you are taller than average, average, or shorter than average.”

She now gives them another challenge:

“Suppose that the ten numbers I just gave you are the heights of ten students. You just computed their average. How does the height of each student compare with the average?”

Der panics. He doesn’t remember the ten numbers. Dee, however, has them all recorded in her notebook. She quickly performs ten subtractions on her calculator and notes the differences. By the way, these differences are called deviations.

A program for Der’s computations

Der did not need to record the ten numbers to compute the sum and subsequently the average of the ten numbers. But his approach did not allow him to find the deviation of each student’s height from the average height. The code given below performs Der’s computations. Run the code.

Get hands-on with 1200+ tech skills courses.