Java Code Example: average of an array

To find the average of an array, a for loop is used to loop through the array and sum up the array entries. The sum is then divided by the number of array elements to get the average.

import java.util.Scanner;

public class ArrayAverage {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		int[] numbers = new int[20];
		int i = 0, result = 0, quantity;

		System.out.print("How many numbers do you want to store in array? (1 - 20): " );
		quantity = reader.nextInt();

		// Store numbers in array (user input)
		for(i = 0 ; i < quantity ; i++) {
			System.out.println("Please enter a number: ");
			numbers[i] = reader.nextInt();
		}

		reader.close();
		
		// Loop over array and sum up the array entries
		for(i = 0; i < quantity; i++) {
			result += numbers[i];
		}
	
		result = result / quantity;

		System.out.println("Average of array is: " + result);
	}
}
Output
How many numbers do you want to store in array? (1 - 20): 6
Please enter a number: 
10
Please enter a number: 
20
Please enter a number: 
30
Please enter a number: 
40
Please enter a number: 
50
Please enter a number: 
60
Average of array is: 35