Program To Find the Sum and Average of an Array

To Find the Sum and Average of an Array, there are following step perform :-

  • Create the Scanner class object for taking input from system.
  • Declare and initialize an array.
  • Declare a sum variable there and initialize it to 0.
  • Update the sum in each iteration from sum+a[i]
  • Print the sum value.
  • For Calculate the average we divide the sum value from number of elements.
  • Print the average value.
				
					import java.util.Scanner;

public class ArrayMain {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		double sum = 0, average;
		int a[] = new int[5];
		System.out.println("enter the number of elements :");
		int n = sc.nextInt();
		System.out.println("enter the elements :" + n);
		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);
	}

}
				
			

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