0

just like thet title says i need the sum of the array using recursion and it's not working .

int somme_elements(int t[10])
{   int static i = -1 ;
    if (i<10)
    {
        i++;
        return t[i] + somme_elements(t+1);
    }

}

int main()
{
  int t[10]={0} ; int i = 0 ;
  /*saisie_tableau(t);/*
  /*afficher_tableau(t);*/
  printf("la somme des valeur du tableau t est %d    ",somme_elements(t));
   return 0;
}

the last printf is supposed to print the sum value . but it's always a really big number or just doesn't make any sense . thank you guys

  • When `i` is `9` you enter the `if` block, increment `i` and try to access `t[10]` which does not exist. – pmg Jan 16 '21 at 14:11

1 Answers1

0

Try

int somme_elements(int t[10])
{   int static i = -1 ;
    if (i<10)
    {
        i++;
        return t[i] + somme_elements(t);
    } else return 0;
}

If i<10 is true, just call the function again and the incremented static i will point the next item.
If i<10 is false, the function will return 0, null for addition.

Note: I just keep the original question indent and format (in 2021-01-16).

Naivre
  • 97
  • 7
  • But I don't like to use static variables to that! – Naivre Jan 16 '21 at 03:04
  • thanks it works . could you please explain to me why i had to add the else return 0 ? i don't really need it i think .since the first if should do the trick . thanks – Ilies Bekhtaoui Jan 16 '21 at 03:21
  • Well, if you don't use return, the compiler can return an undesirable value... In C, better and easy to specify a return! (https://stackoverflow.com/questions/9003283/returning-from-a-void-function) – Naivre Jan 16 '21 at 03:28
  • but if i return 0 . doesn't it mean that the first return doesn't count anymore ? – Ilies Bekhtaoui Jan 16 '21 at 03:31
  • i still have a issue with the notion of the return in recursion . because sometimes with ot without the first return the loop works just fine . – Ilies Bekhtaoui Jan 16 '21 at 03:34
  • No! Only the last call will be 0! That is the magic of recursion! – Naivre Jan 16 '21 at 03:34
  • To understand recursive function, I think about 2 cases: base and recursive cases. So I give a return to each case... (https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/) – Naivre Jan 16 '21 at 03:39