Java Program to Find Sum and Average of an Array

Learn how to create a Java Program to Find Sum and Average of an Array . In Java, an array is used to store multiple values of the same data type. Sometimes we need to calculate the sum and average of all array elements.

Code Explanation (Step-by-Step)

  • Create a Scanner class object to accept user input.
  • Declare an integer array a[] to store the entered elements.
  • Read the number of elements using the sc.nextInt() method.
  • Declare a variable sum and initialize it to 0.
  • Use a for loop to traverse the array and read each element.
  • Add each element to the sum variable using sum = sum + a[i].
  • Display the total sum of all array elements.
  • Calculate the average using the formula: Average = Sum / Number of Elements
  • Store the result in the average variable.
  • Display the calculated average.
				
					import java.util.Scanner;

public class ArrayMain {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        double sum = 0, average;

        System.out.println("Enter the number of elements:");
        int n = sc.nextInt();

        int a[] = new int[n];

        System.out.println("Enter the elements:");
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            sum = sum + a[i];
        }

        System.out.println("Sum is: " + sum);

        average = sum / n;
        System.out.println("Average is: " + average);

        sc.close();
    }
}
				
			

Output :-
enter the number of elements :
2
enter the elements :2
3
4
sum is :- 7.0
average is :- 3.5

Java 8 Program to Find Sum and Average of an Array

				
					import java.util.Arrays;
import java.util.Scanner;

public class ArraySumAverage {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of elements:");
        int n = sc.nextInt();

        int[] a = new int[n];

        System.out.println("Enter the elements:");
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }

        int sum = Arrays.stream(a).sum();
        double average = Arrays.stream(a).average().orElse(0.0);

        System.out.println("Sum is: " + sum);
        System.out.println("Average is: " + average);

        sc.close();
    }
}