Answer the question
In order to leave comments, you need to log in
What is the fundamental difference between nested loops and recursion?
What's up, software.
Did recursion come after cycles, or did cycles replace recursion?
In some functional languages, there are no cycles as such at all, and repetition is implemented by recursion.
So, what is the difference and in which cases is it preferable?
I heard that such questions sometimes slip in the interview.
Answer the question
In order to leave comments, you need to log in
For a spherical problem in a vacuum and an ideal platform, there is no difference. All tasks that can be solved iteratively (loop) can be implemented recursively. In practice, things are a little different. As a rule, everything will be buried in how recursion is implemented on a specific platform. For example, if on each call a pointer to a function is placed on the stack, which must be called recursively, then there is a risk that the stack will overflow and cause an exception BEFORE the recursion starts to unwind. It is more important for a programmer to know when an algorithm recursively looks prettier and more transparent than iteratively. For example, the calculation of factorial is, by definition, recursive. You can solve iteratively, but the algorithm will not directly fall on the definition of the factorial.
First, cycles were invented. Then recursion.
I would say so. The fundamental difference is that a loop is always the repeated execution of the same code.
In recursion, you can implement a much more complex algorithm, we can say that recursion is a more "smart" cycle that implements "deepening into itself", its various levels of deepening. Repetition - yes, but this code is no longer the same as in the loop, it is already code at a different level.
In practice, recursion allows you to much more accurately describe some processes, or the mechanics of processing this real process. And in conjunction with OOP, this is also a very big relief in software development, and a reduction in the amount of written code.
recursion - a function call from this function itself, with all the consequences in the form of stack clogging
in general, either recursion or a cycle may be preferable in different cases. cycles are usually preferable if it is known in advance that the number of repetitions is very large
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question