In: Computer Science
Define what an array index value is in JAVA. Then, write a JAVA program that passes an array to a method and finds the average value or mean value (add up the numbers in the array and divide by the number of values) of the array and prints it out.
If an array A has n elements, the elements in array A can be accessed by array index starting from 0 to n-1. Thus A[0] is the first element, A[1] is the second element and so on.
The following program shows how to calculate average for numbers in an array.
public class Average {
public static double calculateAvg(int[] nums) {
double avg = 0;
int n = nums.length;
for(int i = 0; i < n; i++)
{
avg +=
nums[i];
}
avg = avg / n;
return avg;
}
public static void main(String[] args) {
int[] nums = {2, 3, 4, 5,
10};
System.out.println("Average = " +
calculateAvg(nums));
}
}
output
=====
Average = 4.8