Java Program to find out the average of n numbers using array


April 10, 2022, Learn eTutorial
1108

Here we are explaining how to write a java program to find out the average of the array elements. It's a simple program. Here first we read the limit of the array and read the array elements. Then we will find out the sum of the elements. After that, we have to calculate the average as avg=sum/n.Then display the average of the array elements as avg.

How to declare a one-dimensional array in java?

The syntax of declaring one-dimensional array in java is shown below.

datatype array_name[];

OR

datatype[]  array_name;

Here the data type can be integer, float, double, or any other primitive or user-defined datatype.

How to implement the java program to find out the average of the array elements?

First, we have to declare the class ArrayAvg.Then open the main function. Create an object of the scanner class as a scanner. Declare avg as a float. Read the limit of the array into the variable n. Then read the numbers into the array array[] using for loop. Then used by another for loop to find out the sum of the array elements as sum=sum+num. After that, calculate the average as avg=sum/n.Then display the average as avg.

ALGORITHM

STEP 1: Declare the class ArrayAvg with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer array array[].

STEP 4: Declare the integer variable sum,n.

STEP 5: Declare avg as a float.

STEP 6: Read the limit of the array into the variable n.

STEP 7: Read the elements of the array, by using for loop.

STEP 8: Find out the sum of the array by using for loop as sum=sum+num.

STEP 9: Calculate average as avg=sum/n.

STEP 10: Display average as avg.

 

Java Source Code

                                          import java.util.Scanner;
public class ArrayAvg {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        int[] array = new int[50];
        int sum = 0, n;
        float avg;
        System.out.println("Enter the limit of the array:");
        n = scanner.nextInt();
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }
        scanner.close();
        for (int num: array) {
            sum = sum + num;
        }
        avg = sum / n;
        System.out.println("average of the elements in the array:" + avg);
    }
}
                                      

OUTPUT

Enter the limit of the array:4
Enter the elements of the array:
1
2
3
4
average of the elements in the array:2.0