0

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() : "";
        }
    }
Javad-M
  • 456
  • 6
  • 22
  • In general prefer iteration (loops) over recuresion. Recursive calls are using the stack which is limited in size and might overflow. – wohlstad Jun 22 '22 at 10:05
  • 1
    Recursive calls don't cause memory "leakage" as such. They can cause increased memory usage, since all the data for the previous recursive calls stays on the stack - and also note that stack space is extremely limited compared to heap space. Loops are almost always better for memory usage (but might make the code harder to understand). – Matthew Watson Jun 22 '22 at 10:06
  • In your case, the recursion actually makes things much harder to understand. – Matthew Watson Jun 22 '22 at 10:07
  • Matheew But in my case stack is not occured, yes? – Javad-M Jun 22 '22 at 10:23
  • AFAIK C# still does not support [tail recursion optimization](https://stackoverflow.com/a/491463/2501279) so I would argue that it is preferable to use non-recursive approaches. – Guru Stron Jun 22 '22 at 10:52
  • @MatthewWatson what makes you say that? To me it looks like the runtime would allocate stackspace for the return values of `Console.ReadLine()` and `int.Parse()`. A stackoverflow might be unrealistic due to the huge number of required user inputs, but it doesn't seem impossible to me. – Good Night Nerd Pride Jun 22 '22 at 11:26
  • @GoodNightNerdPride I say that because the current code only recurses 9 times. Clearly that's not going to cause a stack overflow. – Matthew Watson Jun 22 '22 at 13:54
  • @MatthewWatson ah ok, I missed that hard limit and thought you were referring to some optimizations the runtime would apply in the example. Thanks for clearing it up! – Good Night Nerd Pride Jun 23 '22 at 09:57
  • @GoodNightNerdPride why you think this code occurs 9 times? It checks if the user entered a number bigger than 9 or not. If user enters a value bigger than 9 it can continue forever. – Javad-M Jun 23 '22 at 10:10
  • @Javad-M Yes, you're right - I misread that it will keep recursing until the user enters a value less than or equal to 9. So in theory it *could* run out of stack space, if the user keeps entering values greater than 9 for long enough. – Matthew Watson Jun 23 '22 at 12:43

2 Answers2

0

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.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57
0

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:

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.

YungDeiza
  • 3,128
  • 1
  • 7
  • 32