Recursive function to calculate the mean

Asked

Viewed 750 times

1

I did that job media() that averages the elements present in a vector of 5 elements. However, the function is returning 2 instead of the correct average.

#include <stdio.h>

int media(int vet[], int tam);

int main() {
  int vet[5] = {4, 2, 1, 6, 7};

  printf("%d", media(vet, 5));

  return 0;
}

int media(int vet[], int tam) {
  if (tam == 0)
    return 0;
  else
    return vet[tam - 1]/5 + media(vet, tam - 1);
}
  • Just a personal detail, when I wrote "The function is returning..." I meant: "The function is returned 2 instead of the average".

  • Note that you are working with integers. Of its 5 values only 2 are greater than 5, but they are less than 10, and therefore the division will result in 1, in the others (less than 5) the division will return 0. Hence its result will be 2.

1 answer

1


Recursion is not suitable for doing this type of algorithm. In general this is asked as an exercise to learn the mechanism, but then one learns to decide on the wrong use. It is much simpler to do it iteratively. If the sum was done recursively and then divided to find the mean it would be acceptable.

But as the exercise unwinds and asks recursion I will answer what he asks. There is an error there because the division can only occur at the end of the process, that is, when you are at the first call of the function, which is where the recursion will be closed, so you need one more condition to test if you are at that execution.

#include <stdio.h>

int media(int vet[], int posicao) {
    if (posicao == 0) return 0;
    else if (posicao == 5) return (vet[posicao - 1] + media(vet, posicao - 1)) / 5;
    else return vet[posicao - 1] + media(vet, posicao - 1);
}

int main() {
    int vet[5] = {4, 2, 1, 6, 7};
    printf("%d", media(vet, 5));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I changed the variable name also because it is not the size but the position you are dealing with at that time. Doesn’t change the execution, but makes the code much more readable.

Just to compare the iterative form as it is simpler and more DRY (recursive may be more DRY, but it gets more complicated):

#include <stdio.h>

int media(int vet[]) {
    int soma = 0; 
    for (int i = 0; i < 5; i++) soma += vet[i]; 
    return soma / 5; 
}

int main() {
    int vet[5] = {4, 2, 1, 6, 7};
    printf("%d", media(vet));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.