I’m writing a C code for improving recursive functions learning. My function must calculate the average of a set of numbers received in an array. I got to calculate the sum of the numbers in the array, even to return it, same I got to calculate the average inside the function (I’ve printed it) but when I do the return, the main function always gets a trash number.
This is my code:
#include <stdio.h>
#include <stdlib.h>
float sum (int array[], int n)
{
float f; float z=n;
if (n==0) return (array[n]);
f=(array[n]+sum(array,n-1));;
return f/z;
}
int main ()
{
int *array, n, i;
float result;
printf("\nDimension de tu array: ");
scanf("%d", &n);
array=(int *) malloc (n*sizeof (int));
for (i=0; i<n; i++)
{
printf("Valor en A[%d]: ", i+1);
scanf("%d", &array[i]);
}
result=sum(array,n);
printf("\n\nEl promedio es igual a: %f ", result);
}
The problem is here:
Your function is supposed to compute the sum, but you are already dividing by the # of elements.
Change it to:
And divide by the # of elements in your main:
And the other error is here:
should be (and indented):
The last index of an array is
n - 1, notn.