Motivation
In this lesson, we look at a simple problem where the solution needs a Java array.
We'll cover the following
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:
She now gives them another challenge:
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 1400+ tech skills courses.