Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.2 Data sets — averaging values

Lesson

The average of a data set

A data set is a collection of values — for example, a class's exam scores. To find the average (mean), add up all the values and divide by how many there are (scores.length). Compute it as a double: cast the sum to double before dividing, so the decimal part is kept instead of being dropped by integer division.


Worked example

You can visit every value with an enhanced for loop (for-each), which hands you each value in turn — no index needed:

int[] scores = {85, 90, 95, 100};
int sum = 0;
for (int s : scores) {   // s takes each score in turn
    sum = sum + s;
}
double avg = (double) sum / scores.length;   // 370 / 4 = 92.5
System.out.println(avg);

The sum is 370; dividing as doubles gives 92.5. Without the cast, 370 / 4 is integer division and would give 92. (An indexed for loop works too, but for-each is cleaner when you don't need the index.)


▶ Try it: run this to see the average. Change the scores and re-run — the average follows, decimals and all.



The enhanced for loop for (int s : scores) gives you...


To keep the decimal part of an average, you divide as...


Type exactly what this program prints.

int[] d = {60, 70, 80};
int sum = 0;
for (int s : d) {
    sum = sum + s;
}
System.out.println((double) sum / d.length);

If sum and count are both int, then sum / count gives...


True or false?