0

Greetings programming community,

How can I get this recursive function that finds the average of an array from any range using specific parameters to work? The parameters are (int a[], int x, int y). The x parameter means begin at and the y means end at.

int k; //no global variables

int average(int A[], int s, int e) {

    int x = e+1;

    if(s == e) return (k += A[s])/x ;
    k += A[s];
    average(A, s+1, e);
}




int main() {

    int A[5] = {5,7,8,10,2};
    cout << average(A,0,4) << endl;

    return 0;
}

Edited by Singularity83: edits

2
Contributors
3
Replies
17
Views
2 Years
Discussion Span
Last Post by Singularity83
0

What is the purpose of the 3rd parameter 'e'? Also, in your average() function, you don't return the results of the recursive call. IE, line 9 should be return average(A, s+1, e);

0

When I edited the code I didn't edit the parameters. s means start, e means end.

0

This function may require more than one base case. I know if start and end are both equal to one another then the average is obviously that number at that index..
if(s == e) return A[s] or A[e]. I'm not sure how to calculate the total or average without using a global variable. Every time I recursively call the function, the value will be lost.

Edited by Singularity83: edit

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.