This is a Java Program to Calculate Sum & Average of an Array.
Enter size of array and then enter all the elements of that array. Now using for loop we calculate sum of elements of array and hence we divide it by number of elements in array to get average.
Here is the source code of the Java Program to Calculate Sum & Average of an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Sum_Average
{
public static void main(String[] args)
{
int n, sum = 0;
float average;
Scanner s = new Scanner(System.in);
System.out.print(“Enter no. of elements you want in array:”);
n = s.nextInt();
int a[] = new int[n];
System.out.println(“Enter all the elements:”);
for(int i = 0; i < n ; i++)
{
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:"+sum);
average = (float)sum / n;
System.out.println("Average:"+average);
}
}
Output:
$ javac Sum_Average.java
$ java Sum_Average
Enter no. of elements you want in array:5
Enter all the elements:
4
7
6
9
3
Sum:29
Average:5.8