0

Hi,everybody
I am a beginner in c++;Could you please tell me how to change an iteration program to a recursive one and vice versa?It will be greatly appreciated if you could show me with the help of a few examples(programs).

4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Salem
0

If this is the original function

int foo(int x)
{
    while(x < 10)
      x = x + 1;
   return x;
}

Then you can do this:

int foo(int x)
{
    if(x < 10)
    {
        x = x + 1;
       foo(x);
    }
    return x;
}
0

@ Ancient Dragon, the recursive function is incorrect. foo(x) has to return int. The correct version would be

int foo(int x)
{
    if(x < 10)
    {
        x = x + 1;
      return foo(x);
    }
    return x;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.