RR_
RR_

Reputation: 59

C# recursive method converting to loop

I wrote this recursive method but the problem is i need to do the same with a loop. First one is recursive, and the second one is loop but it`s not good. Any advice how to fix the loop method?

double SR(int n)
{
    if (n > 1)
        return Math.Sqrt(2 + SR(n - 1)); 
    else    
        return Math.Sqrt(2);  
}//recursion



double SR2(double n)
{
    if(n > 1)
    {
        do
        {
            n = Math.Sqrt(2+Math.Sqrt(n - 1));
        }
        while(n <= 1);
    }
    else
    {
        n = Math.Sqrt(2);
    }

    return n; //loop
}

Upvotes: 0

Views: 445

Answers (2)

NothingsImpossible
NothingsImpossible

Reputation: 781

Explaining Knaģis answer:

You need to grasp more the concept of recursive functions.

In general recursive functions have a notion of "base" or "stop" condition, that is, a "fixed" value the function returns when a specified condition is met, otherwise, it would continue indefinitely.

When converting to a loop, the base condition becomes the starting value of the loop. So in the looped version, Math.Sqrt(2) becomes the starting value of n.

From there, we loop until the desired value is achieved. How to determine when to stop? In the original recursive function, the stop condition is "n <= 1" (beware, its the condition for the "else" to be reached, so its the inverse of your if). Also, in each iteration, the function receives "n - 1" as argument. So what is happening is we are decrementing n by 1 until it reaches 1; so the loop will be executed (n - 1) times. To be more clear on this point, the loop could be rewritten with for (var i = 0; i < (n-1); i++) . The effect is the same and it is more clear that the loop executes (n-1) times.

Also, check this link for more info.

Upvotes: 2

Knaģis
Knaģis

Reputation: 21495

double SRloop(int n)
{
    var r = Math.Sqrt(2);

    for (var i = 2; i <= n; i++)
    {
        r = Math.Sqrt(2 + r);
    }

    return r;
}

Upvotes: 3

Related Questions