nerd
nerd

Reputation: 11

concept of recursion

colour[5]={0};

void _do()
{
   colour[i]=1;
   for(int i=0;i<5;i++){
    _do(i);
   }
}

My ques is, while the last recursion is finished, then we would start our journey to go from last to first.What we would see when we get back to prvious call? Will we get all colours set to 1 ? or we wud get the remaining 0 those weren't call at that function.

The ques is, if we update an array in a call, will we get that updated while returning back to previous call?or we would get the previous version of that array?

Thank you in advance.

Upvotes: 0

Views: 308

Answers (4)

Mephane
Mephane

Reputation: 2022

You're breaking the basic concept of recursion here - to recurse instead of iterating. This is how you'd do it:

int colour[5]={0};

void _do(int i)
{
  if (i < sizeof(colour))
  {
    colour[i]=1;
    _do(i + 1);
  }
}

Basically, you either iterate, or recurse. Which one is better depends on the situation, type of data structure, the way other functions you're using behave etc.

In this specific case, I'd usually iterate, however.

On the specific question: The function's side effect is to modify the array colour, which means all modifications will immediately apply to that array automatically.

Upvotes: 0

tmiddlet
tmiddlet

Reputation: 296

to start the journey back you need to have an if statement that starts at the very beginning of the function and actually return a value when that statement us true.

Upvotes: 1

Larry Osterman
Larry Osterman

Reputation: 16142

First off, the code won't compile - at line 5, you reference "i" without declaring it (that happens at line 6).

Even if you fixed it, the code would infinitely recurse - you'd hit the first iteration of the "for" loop, call _do(1) which would then enter the "for" loop and call _do(1) again.

Upvotes: 2

Yuval
Yuval

Reputation: 8097

If the array is defined outside the recursive method, it would remain changed when the recursion is done. If it is defined within a step of the recursion (inside the method) and not returned, the changes will have never occurred.

Upvotes: 0

Related Questions