Problem of the Day
Wednesday, January 21, 2026
Problem:
Consider the following code, which is intended to print out the average of the integers in an array.
// PRECONDITION: array length is > 0
int sum = 0; # sums the values in the integer array
for (int el : arr)
{
sum += el;
}
double average = sum / arr.length;
System.out.println(average);
Why won't this code work correctly?
- it calculates incorrectly for an odd number of values
- it calculates incorrectly for an even number of values
- it calculates incorrectly if the average is an integer
- it calculates incorrectly if the average is not an integer
The correct answer is d. As written, the code uses a division of two integer values, which produces an integer result. For any collection of values where the average is not an integer—the average of 2 and 3 is 2.5, for example—the integer division will not produce the correct result.
Note that storing the result from the integer division in a variable of the type double doesn't help. The integer division has already been performed, so average simply stores that result in double form.