Java program to find the average of elements in an array

Finding the average of elements in an array is a common programming task that helps you understand array manipulation and basic arithmetic operations in Java. Below is a detailed Java program to find the average of elements in an array.

Java Program to Find the Average of Elements in an Array

import java.util.Scanner;

public class AverageOfElementsInArray {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the size of the array
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        // Create an array of the given size
        int[] array = new int[size];

        // Prompt the user to enter the elements of the array
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < size; i++) {
            array[i] = scanner.nextInt();
        }

        // Find the average of elements in the array
        double average = findAverageOfElements(array);

        // Print the average of elements
        System.out.println("The average of elements in the array is: " + average);
    }

    // Method to find the average of elements in an array
    public static double findAverageOfElements(int[] array) {
        // Initialize sum to 0
        int sum = 0;

        // Traverse through the array and add each element to sum
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }

        // Calculate the average
        double average = (double) sum / array.length;

        return average;
    }
}
Java program to find the average of elements in an array
Java program to find the average of elements in an array

Explanation of the Code

Let’s break down the program step-by-step to understand how it works.

  1. Importing the Scanner Class: We import the Scanner class from the java.util package to read input from the user.
import java.util.Scanner;

2. Creating the Main Class: We create a public class named AverageOfElementsInArray. In Java, the class name should match the filename.

public class AverageOfElementsInArray {

3. Main Method: The main method is the entry point of the program. Inside this method, we will write the code to find the average of elements in an array.

public static void main(String[] args) {

4. Creating a Scanner Object: We create a Scanner object to read input from the user.

Scanner scanner = new Scanner(System.in);

5. Reading the Size of the Array: We prompt the user to enter the size of the array and store this value in a variable.

System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

6. Creating an Array: We create an array of the given size.

int[] array = new int[size];

7. Reading the Elements of the Array: We prompt the user to enter the elements of the array and store these values in the array.

System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
    array[i] = scanner.nextInt();
}

8. Finding the Average of Elements: We call the findAverageOfElements method to find the average of elements in the array. The result is stored in a variable average.

double average = findAverageOfElements(array);

9. Printing the Average of Elements: We print the average of elements in the array.

System.out.println("The average of elements in the array is: " + average);

10. Method to Find the Average of Elements in an Array: The findAverageOfElements method finds the average of elements in the given array. This method works by first calculating the sum of all elements in the array and then dividing this sum by the number of elements to find the average.

public static double findAverageOfElements(int[] array) {
    // Initialize sum to 0
    int sum = 0;

    // Traverse through the array and add each element to sum
    for (int i = 0; i < array.length; i++) {
        sum += array[i];
    }

    // Calculate the average
    double average = (double) sum / array.length;

    return average;
}

Explanation of the findAverageOfElements Method

  1. Initializing the Sum Variable: We initialize the sum variable to 0.
int sum = 0;

2. Traversing the Array: The for loop iterates through each element of the array. In each iteration, we add the current element to the sum variable.

for (int i = 0; i < array.length; i++) {
    sum += array[i];
}

3. Calculating the Average: After the loop finishes, we calculate the average by dividing the sum by the number of elements in the array. We cast sum to double to ensure the division is done in floating-point arithmetic.

double average = (double) sum / array.length;

4. Returning the Average: We return the average variable, which now holds the average of all elements in the array.

return average;

Running the Program

To run the program, follow these steps:

  1. Save the code in a file named AverageOfElementsInArray.java.
  2. Open a command prompt or terminal and navigate to the directory where you saved the file.
  3. Compile the program using the following command:
javac AverageOfElementsInArray.java

4. Run the compiled program using the following command:

java AverageOfElementsInArray
  1. Follow the prompts to enter the size and elements of the array. The program will display the average of elements in the array.

Example Output

If you run the program and enter the following input:

Enter the size of the array: 5
Enter the elements of the array:
10
45
32
67
29

The output will be:

The average of elements in the array is: 36.6

What did we learn from this article?

Finding the average of elements in an array is a fundamental exercise that helps in understanding array manipulation and basic arithmetic operations in Java. This Java program demonstrates how to find the average of elements in an array by first calculating the sum of all elements and then dividing the sum by the number of elements. By practicing such basic programs, you can strengthen your problem-solving skills and gain confidence in your ability to write efficient Java code. Keep practicing and exploring more problems to enhance your programming skills.

Leave a Comment