Average of an Array
Problem
Read a count n and then n integers. Print the average of the integers with 2 digits after the decimal point. If n is 0, print Array is empty.
Constraints
- 0 <= n <= 10^5
- -2^31 <= element < 2^31
Examples
Input
5 3 4 5 7 9
Output
5.60
Input
0
Output
Array is empty
Solutions
We add all elements into a long, then divide as decimal numbers. The original program used integer division, so 28 / 5 printed 5.0 instead of 5.6.
/*
* Problem : Calculate the average of the elements of an array.
* Input : First line is n (number of elements). Second line has n integers.
* Output : The average with 2 digits after the decimal point, or "Array is empty".
* Approach: Add all elements, then divide the sum by the count using decimal division.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Locale;
import java.util.Scanner;
public class Main {
// This method receives an array and returns its average as a decimal number.
static double average(int[] array) {
// Step 1: Use a long for the sum, because many large int values can overflow an int.
long sum = 0;
// Step 2: Visit every element of the array and add it to the sum.
for (int element : array) {
sum = sum + element;
}
// Step 3: Divide as decimal numbers. Integer division would drop the decimal part.
// Example: 28 / 5 = 5 with integers, but 28.0 / 5 = 5.6 with decimals.
return (double) sum / array.length;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
// Edge case: an empty array has no average, so we stop here.
if (count == 0) {
System.out.println("Array is empty");
return;
}
int[] array = new int[count];
for (int i = 0; i < count; i++) {
array[i] = scanner.nextInt();
}
// Locale.US makes sure the decimal separator is a dot on every computer.
System.out.println(String.format(Locale.US, "%.2f", average(array)));
}
}
Hints (3)
- Add all elements first. Then think about what the division should return.
- Dividing two integers in Java drops the decimal part. Make one side a decimal number.
- Check the empty array before you divide. Dividing by zero is a problem.