Problems with recursion in c

2

I'm trying to learn recursion and am in doubt on an issue I was doing in c, I need to add how many numbers of a vector with n elements are larger than a number x. This recursion simply does not go into the head, I need a clearing.

#include <stdio.h>
#include <stdlib.h>

int busca(int v[], int n, int k)
{
  int x = 0;
  if(n == 1)
  {
    if( k < v[0])
     x= x + 1;



    }


  else
  {  
    if(k <  v[n])
      x = x+ 1;
      busca( v, n-1 ,k);
    }



      return x;


}


int main()
{
  int n, k,x;



  printf("DIGITE A QUANTIDADE DE ELEMENTOS DO VETOR:");
  scanf("%d", &n);

  int v[n];
  int i;

  for(i = 1; i <= n; i++)
  {
    printf("Digite o elemento %d: ", i);
    scanf("%d", &v[i]);
  }

  printf("Digite um numero: ");
  scanf("%d", &k);


//printf ("%d",
printf("x = %d", busca(v, n, k));

  return 0;
}
    
asked by anonymous 11.11.2017 / 13:27

1 answer

1

The recursion you want to do boils down to the following logic:

  • Verify that the item you are going to is greater than k and count 1 if it is 0 otherwise
  • Call the same function recursively to the next element by adding its result

Implementation:

int busca(int v[], int n, int k) {
    if (--n<0) return 0; //se chegou ao fim retorna 0

    return (v[n]>k?1:0) + busca(v, n, k);//contabilizar 0 ou 1 e somar com a próxima busca
}

main is accessing the array outside of valid positions:

for(i = 1; i <= n; i++)

It is ranging from 1 to n , but arrays start in 0 . Then you have to start with 0 and go to n-1 .

After this adjustment we get the main like this:

int main() {
    int n;
    printf("DIGITE A QUANTIDADE DE ELEMENTOS DO VETOR:");
    scanf("%d", &n);

    int v[n], i, k;    
    for(i = 0; i < n; i++) {
        printf("Digite o elemento %d: ", i);
        scanf("%d", &v[i]);
    }

    printf("Digite um numero: ");
    scanf("%d", &k);
    printf("x = %d", busca(v, n, k));

    return 0;
}

See the Ideone example

    
11.11.2017 / 15:08