Array Average Calculation

This program calculates the average of array elements.

Problem Statement

Write a Java program to calculate the average of elements in an integer array.

Source Code

1 public class ArrayAverage {
2 public static void main(String[] args) {
3 int[] arr = {10, 20, 30, 40, 50};
4 int sum = 0;
5 for(int i=0; i<arr.length; i++) {
6 sum += arr[i];
7 }
8 double avg = (double)sum / arr.length;
9 System.out.println("Average of array elements: " + avg);
10 }
11 }

Program Output

Average of array elements: 30.0

Explanation

The variable sum accumulates all elements, and the average is calculated by dividing sum by arr.length with a type cast to double ensuring decimal precision, together demonstrating average calculation using arrays.

Quick Links to Explore