305,981 views
18 votes
18 votes
Write a method, including the method header, that will receive an array of integers and will return the average of all the integers. Be sure to use the return statement as the last statement in the method. A method that receives an array as a parameter should define the data type and the name of the array with brackets, but not indicate the size of the array in the parameter. A method that returns the average value should have double as the return type, and not void. For example: public static returnType methodName(dataType arrayName[]) 3 The array being passed as a parameter to the method will have 10 integer numbers, ranging from 1 to 50. The average, avgNum, should be both printed in the method, and then returned by the method. To print a double with 2 decimal points precision, so use the following code to format the output: System.out.printf("The average of all 10 numbers is %.2f\\", avgNum);

User Viktor Bahtev
by
2.7k points

2 Answers

11 votes
11 votes

Final answer:

The method 'calculateAverage' takes an array of integers, calculates the sum, divides by the number of elements to get the average, prints it using printf, and returns the average as a double.

Step-by-step explanation:

To calculate the average of an array of integers, we can define a method that takes the array as a parameter. Below is the method that fulfills the criteria:

public static double calculateAverage(int[] array) {
int sum = 0;
for (int num : array) {
sum += num;
}
double avgNum = sum / (double) array.length;
System.out.printf("The average of all 10 numbers is %.2f\\", avgNum);
return avgNum;
}

This method first calculates the sum of all integers in the array. Then it calculates the average by dividing the sum by the length of the array, which is cast to a double to ensure a floating-point result. The result is printed with 2 decimal places using System.out.printf, and then the average (avgNum) is returned as a double.

User EricAndTheWeb
by
3.2k points
14 votes
14 votes

Answer:

The method is as follows:

public static double average(int [] arrs){

double sum = 0,avgNum;

for(int i = 0;i<arrs.length;i++){

sum+=arrs[i];

}

avgNum = sum/arrs.length;

System.out.printf("The average of all numbers is %.2f\\", avgNum);

return avgNum;

}

Step-by-step explanation:

This defines the method

public static double average(int [] arrs){

This declares sum and avgNum as double; sum is then initialized to 0

double sum = 0,avgNum;

This iterates through the array

for(int i = 0;i<arrs.length;i++){

This adds up the array elements

sum+=arrs[i]; }

This calculates the average

avgNum = sum/arrs.length;

This prints the average to 2 decimal places

System.out.printf("The average of all numbers is %.2f\\",

avgNum);

This returns the average to main

return avgNum; }

User Jilyan
by
3.1k points