Home > Software design >  Loop or Recursive method? Which one is better to use?
Loop or Recursive method? Which one is better to use?

Time:06-22

I want to ask user to enter a value less than 10. I am using the following code. Which one is better to use? Loop or Recursive method. Someone said me using Recursive function method may cause Memory Leakage. Is it true?

 class Program
    {
        static void Main(string[] args)
        {
            int x;
            do
            {
                Console.WriteLine("Please Enther a value less than 10.");
                x = int.Parse(Console.ReadLine());
            } while (x > 10);

             //Uncomment the bellow method and comment previous to test the Recursive method
             //Value();
        }
        static string Value()
        {
            Console.WriteLine("Please Enther a value less than 10.");
            return int.Parse(Console.ReadLine()) > 9 ? Value() : "";
        }
    }

CodePudding user response:

It would probably be a long time before recursion became an issue in this example.

Recursive methods run the risk of causing stack overflow exceptions if they keep running for a long time without completing. This is because each method call results in data being stored on the stack (which has very limited space) - more info here:

https://en.wikipedia.org/wiki/Stack_overflow#:~:text=The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.

In your case unless they enter a number greater than or equal to 10 loads of times or you have very little memory it should be fine.

Generally it's better to use loops than recursion as they are simpler to understand. Recursion is a useful tool for achieving good performance in certain scenarios but generally loops should be preferred.

CodePudding user response:

Recursive functions are used when you have a base case and a regular case. The base case is vital, since it marks the end of recursion. For example, you can create a function factorial(n) to calculate the factorial of a number n. The base case happens when n reaches 1 and you just return 1, while in the regular case you just multiply n by factorial(n - 1).

In general (there are a few optimization cases in which you can save memory), recursive functions create a new stack frame for each call. So, for factorial(3), there are at least three stack frames being created, the factorial(3) itself, the factorial(2) one, and finally the one that finished recursions which would be factorial(1).

At least, in that case you know when you are going to finish, and how much memory you need, so a compiler can work with that in advance.

All that discussion above means that you are misunderstanding recursion if you think you can use it in order to validate user input. There can be only one call with the correct answer, which would be the base case, or even hundreds or thousands or regular case instances as well. This has the potential of overflowing the stack of your program, without any way to prevent that, on the part of the compiler or on your part.

Another way to see this is that recursion is used as a way of abstraction: you specify what needs to happen, even near to the mathematical problem, and not how it should happen. In your example, that level of abstraction is unneeded.

  • Related