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).

Recommended Answers

All 3 Replies

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;
}

@ 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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.