简体   繁体   中英

Finding Average of Array of integers using recursion

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

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.

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;
}
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);
}
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM