AMH9 - 4 months ago 40

Java Question

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

Answer

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;
}
```