Java Code Example: average of an array

This Java program calculates the average of numbers stored in an array. Here’s an explanation of the code:

  1. Import the java.util.Scanner class to enable user input.
  2. Create the ArrayAverage class, and inside it, the main method.
  3. Create a Scanner object reader to get input from the user.
  4. Declare an array numbers of 20 elements, an integer result initialized to 0, and another integer quantity to store the number of elements the user wants to store in the array.
  5. Prompt the user to enter the number of elements they want to store in the array and store it in the quantity variable.
  6. Use a for loop to get the user input and store it in the array numbers. The loop will run quantity number of times.
  7. Close the Scanner reader.
  8. Use another for loop to sum up the elements of the array. The loop will run quantity number of times and add each element of the array to result.
  9. Divide the result by quantity to get the average.
  10. Finally, print out the average by concatenating it with the string “Average of array is: ” and print it out.
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