Write a Java program that implements a method called calculateAverage
that takes an array of integers as a parameter and returns the average of all the integers in the array. The method should be declared as follows:
public static double calculateAverage(int[] numbers)
In your main
method, create an array containing the following integers: [5, 10, 15, 20, 25]
. Call the calculateAverage
method passing the array as an argument and store the returned result in a variable called average
. Finally, print the value of average
to the console.
The average is: 15.0
To compute the average, we need to sum all the integers in the array and then divide the sum by the total number of elements in the array. Here's the step-by-step explanation of the solution:
Define the calculateAverage
method with a return type of double and a single parameter of type int[]
named numbers
.
Inside the calculateAverage
method, declare a variable named sum
of type int
and initialize it to 0. This variable will be used to sum the elements in the array.
Use a for-each loop to iterate over each element num
in the numbers
array.
Inside the loop, add the current element num
to the sum
variable.
After the loop, calculate the average by dividing the sum
variable by the length of the numbers
array and store the result in a variable called average
of type double
.
Return the value of average
from the calculateAverage
method.
In the main
method, create an array of integers called numbers
and initialize it with the values [5, 10, 15, 20, 25]
.
Call the calculateAverage
method, passing the numbers
array as an argument, and store the returned result in a variable called average
.
Print the value of average
to the console using the System.out.println
method.
public class AverageCalculator {
public static double calculateAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
return average;
}
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
double average = calculateAverage(numbers);
System.out.println("The average is: " + average);
}
}
Make sure to save this code in a file named AverageCalculator.java
and run it to see the expected output.