Finding the middle array of integers using recursion
I am trying to find the average of integer elements in an array using recursion. I know how to do this using loops, but I have to do it by recursion for my assignment, so I tried to find the sum of the elements using recursion and then divided the sum by the length of the array. I wrote this code, but it gives me the 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;}
Calling findAvg method in the 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);
}
}
Console output:
Average value of elements = 1
source to share
First of all, the average of integers can be floating point. Therefore, make the return type of your function float or double. Now,
If you have a number set n
with an average x
and you want to add another number to the set (say b
). The 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;
}
source to share
This is sum=a[n-1]+findAvg(a,n-1);
wrong in the first place , because if it findAvg(a,n-1)
returns the correct average for the first (n-1) items, the sum should be a[n-1] + (n-1) * findAvg(a,n-1)
.
Second, you lose precision when dividing integers in avg = sum/n;
Consider using paired numbers.
source to share