samedi 16 juin 2018

C++ 2 nested for loops transform to recursion

Hi i wanted to tranform this code into a recursive function:

int a3(int* a, int length) {
   if(a == 0 || length <= 0) return 0;
   int sum = 0;
   for(int i = 0; i < length; i++) {
      for(int j = i; j < length; j++) {
         sum += a[j];
      }
   }
   return sum;
}

My approach is :

int rec_help(int*a, int length);

int a3(int* a, int length) {
    if(a == 0 || length <= 0) return 0;
else{
    return rec_help(a,length) + rec_help(a+1,length-1) ;
    }
}

int rec_help(int*a, int length){
    if(a == 0 || length <= 0) return 0;
    else{
        int tmp = a[0];
        return tmp + a4(a+1,length-1);
    }
}

But i'm not getting it right.

With a3() i wanted to simulate the first for loop, and i think there is my problem :D

And with rec_help() the second loop and the body, but im mixing things here.

I would appreciate any kind of help :)

Aucun commentaire:

Enregistrer un commentaire