This Java program calculates the average of numbers stored in an array. Here’s an explanation of the code:
java.util.Scanner
class to enable user input.ArrayAverage
class, and inside it, the main method.reader
to get input from the user.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.quantity
variable.numbers
. The loop will run quantity
number of times.reader
.quantity
number of times and add each element of the array to result
.result
by quantity
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);
}
}
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