0

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
}
3
  • the output of both should be equal Commented Nov 30, 2013 at 21:07
  • It is not good because the output is not equal Commented Nov 30, 2013 at 21:12
  • 1
    "It's not good because it doesn't do what I want," isn't a great spot to start with a question about homework. Commented Nov 30, 2013 at 21:13

2 Answers 2

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

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

    return r;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you it explains everything. And it gives me the same output.
A recursive method will always run once so this is not the same.
2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.