3
int foo(int x)
{   
    if (x >= 0)
    {
        return (x - 1) + 2 * foo(x - 1);
    }
    else
    {
        return 1;
    }

}

Hi, I need to rewrite this function such that it will be free of recursion. I tried solving this mathematically, but to no avail. I am new to programming, so any help will be much appreciated. Thanks in advance!

2
  • 3
    what precisely did you try? Are you sure it's not if(x > 0)?
    – Walter
    Oct 14, 2015 at 18:16
  • Consider: f(0)=1 and f(n)=(n-1) + 2*f(n-1). If we know the value of n-1, we know the value of n. Could this be written as a for loop? Oct 14, 2015 at 18:22

1 Answer 1

3

I assume that it really should be if(x>0) in your question.

Then examining your function, we see that foo(0)=1 and otherwise that foo(x)=(x-1)+2*foo(x-1). Thus foo(x) only depends on foo(x-1). So, you can simply use an iteration to progress the result

int foo(int x)
{
  auto result=1;           // result if x=0
  for(int n=0; n!=x; ++n)  // increment result to desired x
    result=n+2*result;     // corresponds to (x-1)+2*foo(x-1) in original
  return result;
}

If it really was if(x>=0) instead, I leave it as an exercise to you to adapt the code.

4
  • 1
    There was a related question yesterday: stackoverflow.com/questions/33096018/…. It appears that if ( x >= 0 ) is right. foo(-1) = 1. It so happens that foo(0) = 1 too.
    – R Sahu
    Oct 14, 2015 at 18:29
  • @Walter Thanks for your help. In the question, its if ( x >= 0) Is there any way to make it adapt to it? Yes @Sahu, it is a related question as per the link you posted.
    – Alan1
    Oct 15, 2015 at 0:54
  • @Alan1 I think you received a lot of help and hints and you should be able to work that out for yourself. Think of what the result for x=-1 will be and start the loop from there. Always check that your recursive and non-recursive functions obtain the same answers.
    – Walter
    Oct 15, 2015 at 7:30
  • @Walter, thanks I have managed to work that out myself. Thank you so much for you help!
    – Alan1
    Oct 16, 2015 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.