I just learned recently arrays. This exercise calls to return an average. I am trying to figure out how to return an average from this method call.
public class Numbers {
// calcAverage() takes in an int array and returns the average value of elements in the array as a double.
public double calcAverage(int[] nums) {
}
public static void main(String[] args) {
Numbers numObject = new Numbers();
int [] nums = {1,2,3,4,5};
System.out.println(numObject.calcAverage(nums));
}
}
The following code resolved the issue:
package testingCode;
public class test {
public double calcAverage(int[] nums) {
double sum;
int i;
sum = 0;
for (i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
sum = sum / nums.length;
return sum;
}
public static void main(String[] args) {
test numObject = new test();
int [] nums = {1,2,3,4,5};
System.out.println(numObject.calcAverage(nums));
}
}
Advertisement
Answer
// calcAverage() takes in an int array and returns the average value of elements in the array as a double.
public double calcAverage(int[] nums) {
int sumOfElements=0;
for (int num: nums){
sumOfElements+=num;
}
return sumOfElements/(double)nums.length;
}
So the algorithm looks like:
- Iterate over all elements in array to create the sum of them.
- Divide the sum of the elements by the total number of elements. Attention! As both are integers it would be an integer division without decimal numbers. (That is why I cast the length to a double)