Finding the average of all elements in an array.
Here’s a Java program that calculates the average of all elements in an array:
public class AverageCalculator { public static void main(String[] args) { int[] numbers = { 5, 10, 15, 20, 25 }; double average = calculateAverage(numbers); System.out.println("Average: " + average); } public static double calculateAverage(int[] array) { int sum = 0; for (int number : array) { sum += number; } return (double) sum / array.length; } }
In this program, we have a method called `calculateAverage` that takes an integer array as input and returns the average as a `double`. It calculates the sum of all elements in the array by iterating over each element using a for-each loop. Finally, it divides the sum by the length of the array to obtain the average.
In the `main` method, we create an array of numbers `{ 5, 10, 15, 20, 25 }`, and then we call the `calculateAverage` method with this array as an argument. The average is stored in the `average` variable, which is then printed to the console.
No comments yet! You be the first to comment.