Sum and Average of Array in Java
Here, you will get the program code to calculate the Sum and Average of array in Java programming.
To calculate sum and average, we will get some n numbers from the user, store in an int Array, and after that calculate the Sum and Average of Array Elements and print the result.
Sum :-
Sum is the total of all the given numbers.
Average : –
Average is the mean value of all given numbers. Formula of average is following:
Average = Sum of all Values / Number of All values
Sum and Average of Array in Java Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.util.*; public class ArraySumAverage { public static void main(String args[]) { int i; double sum=0; Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements:"); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } //Sum of Array Elements for (i = 0; i < arr.length; i++) { sum=sum+arr[i]; } // Average of Array Elements double avg=sum/arr.length; System.out.print("\nSum of Array Elements are : "+sum); System.out.print("\nAverage of Array Elements are : "+avg); } } |
Output
Check out our other Java Programming Examples