Finding Average of Array of integers using recursion
Solution 1
First of all average of integers can be floating point. So make the return type of your function to float or double.
Now,
If you have set of n
numbers with average of x
and you want to add one more number to the set (say b
). New average will be ((n * x) + b) / (n + 1). Use the same trick in your code.
public float findAvg(int a[], int n)
{
float sum,avg;
if(n==1)
{
sum=a[0];
}
else
{
// Calculate sum of n-1 numbers = (n-1) * (avg of n-1 numbers)
// and add nth number to it ( i.e. a[n-1])
sum= a[n-1]+ (n-1) * findAvg(a,n-1);
}
avg = sum/n;
return avg;
}
Solution 2
First of all sum=a[n-1]+findAvg(a,n-1);
is wrong, since if findAvg(a,n-1)
returns the correct average for the first (n-1) elements, the sum should be a[n-1] + (n-1) * findAvg(a,n-1)
.
Second of all, you are losing precision when dividing integers in avg = sum/n;
Consider using doubles.
Solution 3
public double average(int y[], int i) {
double result;
result = (double)y[i] / (double)y.length;
if (i == 0)
return result;
else
return result + average(y, i-1);
}
AMH9
Updated on June 29, 2022Comments
-
AMH9 almost 2 years
I'm trying to find the average of integers elements in an array using recursion. I know how to do it using loops, but I have to do it by recursion for my assignment, so what I tried to do is to find the sum of elements using recursion and then divide the sum by the length of the array. I wrote this code but it gives me a wrong result:
public int findAvg(int a[], int n) { int sum,avg; if(n==1) { sum=a[0]; return sum; } else { sum=a[n-1]+findAvg(a,n-1); } avg = sum/n; return avg;}
The calling of findAvg method in main class:
public class main { public static void main(String[] args) { // TODO Auto-generated method stub Recursive r = new Recursive (); int integersArr [] = {1,2,3,4,5}; int max = r.findMax(integersArr,integersArr.length ); int avg = r.findAvg(integersArr, integersArr.length); System.out.println("Maximum element = "+ max); System.out.println("Average value of elements = "+ avg); } }
The console output:
Average value of elements = 1
-
AMH9 over 9 yearsThank you I edited the sum so that the average returned each time by the recursive call is correct.