Programming why use recursion




















Recursion is a powerful tool, and it's really dumb to use it in either of those cases. If a programmer who worked for me used recursion to compute a factorial, I'd hire someone else. I thought this was a very interesting point to raise and may be a reason why recursion is often misunderstood. People use recursion only when it is very complex to write iterative code.

For example, tree traversal techniques like preorder, postorder can be made both iterative and recursive. But usually we use recursive because of its simplicity. Here's a simple example: how many elements in a set. There's a lot more useful examples traversing a tree, for example which I'm sure other people will cover.

Well, that's a pretty decent definition you have. And wikipedia has a good definition too. So I'll add another probably worse definition for you. When people refer to "recursion", they're usually talking about a function they've written which calls itself repeatedly until it is done with its work.

Recursion can be helpful when traversing hierarchies in data structures. An example: A recursive definition of a staircase is: A staircase consists of: - a single step and a staircase recursion - or only a single step termination. To recurse on a solved problem: do nothing, you're done. To recurse on an open problem: do the next step, then recurse on the rest. You have a lot of apples in front of you on a table and you want to know how many apples there are.

A recursive function is a function that contains a call to itself. A recursive struct is a struct that contains an instance of itself. You can combine the two as a recursive class.

Consider two mirrors facing each other. We've seen the neat infinity effect they make. Each reflection is an instance of a mirror, which is contained within another instance of a mirror, etc. The mirror containing a reflection of itself is recursion. A binary search tree is a good programming example of recursion. The structure is recursive with each Node containing 2 instances of a Node. Functions to work on a binary search tree are also recursive.

This is an old question, but I want to add an answer from logistical point of view i. I use Java for work, and Java doesn't support nested function. As such, if I want to do recursion, I might have to define an external function which exists only because my code bumps against Java's bureaucratic rule , or I might have to refactor the code altogether which I really hate to do.

Thus, I often avoid recursion, and use stack operation instead, because recursion itself is essentially a stack operation. Recursion as it applies to programming is basically calling a function from inside its own definition inside itself , with different parameters so as to accomplish a task.

Recursion is a problem-solving strategy for huge problems, where at every step just, "turn 2 small things into one bigger thing," each time with the same hammer.

Suppose your desk is covered with a disorganized mess of papers. How do you make one neat, clean stack of papers from the mess, using recursion? Notice that this is pretty intuitive, aside from counting everything which isn't strictly necessary.

You might not go all the way down to 1-sheet stacks, in reality, but you could and it would still work. The important part is the hammer: With your arms, you can always put one stack on top of the other to make a bigger stack, and it doesn't matter within reason how big either stack is.

Recursion is the process where a method call iself to be able to perform a certain task. It reduces redundency of code. Most recurssive functions or methods must have a condifiton to break the recussive call i.

Not all functions are suited to be used recursively. Jack manages 2 programmers, John - 3, and Morgan - 5. The answer is obvious - but what if 2 of Morgan-s employees are also managers? HERE comes the recursion. You'll never know, how much cycles will you go before getting an answer, though you know how many managers you have and how many Budget can you spend.

Recursion is a tree, with branches and leaves, called parents and children respectively. When you use a recursion algorithm, you more or less consciously are building a tree from the data. Any algorithm exhibits structural recursion on a datatype if basically consists of a switch-statement with a case for each case of the datatype. Stack Overflow for Teams — Collaborate and share knowledge with a private group.

Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. What is recursion and when should I use it? Ask Question. Asked 13 years, 3 months ago. Active 4 years, 10 months ago. Viewed k times. Mike Minutillo. And maybe this helps: stackoverflow. This may help grasp the concept: navigate to the link provided on the second comment of the question on this page and do what the comments say to do: stackoverflow. Active Oldest Votes. To see why, walk through the steps that the above languages use to call a function: space is carved out on the stack for the function's arguments and local variables the function's arguments are copied into this new space control jumps to the function the function's code runs the function's result is copied into a return value the stack is rewound to its previous position control jumps back to where the function was called Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop.

Good to see an explanation of the inherent overhead of recursion. I touched on that in my answer as well. But to me, the big strength with recursion is what you can do with the call stack. See my answer for an example. Very disappointed to find the top answer to a question titled "What is recursion and when should I use it? You're probably right Dukeling. For context, when I wrote this answer there were many great explanations of recursion already written and I wrote this intending to be an adjunct to that info, not the top answer.

In practice when I need to walk a tree or handle any other nested data structure I usually turn to recursion and I've yet to hit a stack overflow of my own making in the wild. Add a comment. Simple english example of recursion. A child couldn't sleep, so her mother told her a story about a little frog, who couldn't sleep, so the frog's mother told her a story about a little bear, who couldn't sleep, so the bear's mother told her a story about a little weasel There is a similar story like this for little kids who won't fall asleep in Chinese folk tales, I just remembered that one, and it reminds me how real world recursion works.

Christopher: This is a nice, simple example of recursion. Specifically this is an example of tail recursion. However, as Andreas stated, it can easily be rewritten more efficiently with a for loop.

As I explain in my answer, there are better uses for recursion. No, it's only there for clarity. Were it written to pass the length-so-far along, only then could we forget the caller existed.

Add new Point3D x - len, y - len, -len ; mesh. Conclusion In practical terms, recursion makes the most sense whenever you need iterative branching. Good explanation, but I think it's important to note that this is simply tail recursion and offers no advantage over the iterative solution. It's roughly the same amount of code, and will run slower due to the function call overhead. SteveWortham: This isn't tail recursion.

In the recursive step, the result of FactRec has to be multiplied by n before returning. Quoted from the exact article you linked: "A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same or related type," — Amber.

I don't think that is a great explanation, since recursion strictly speaking does not have to solve problem at all. You could just call yourself And overflow.

First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve. Finally, we redo the entire algorithm.

The above example is called tail recursion. This is where the very last statement is calling the recursive algorithm. Tail recursion can directly be translated into loops. Another example of recursion would be finding the maximum value in a list of numbers. The maximum value in a list is either the first number or the biggest of the remaining numbers.

Here is how we would write the pseudocode of the algorithm:. The "work toward base case" is where we make the problem simpler e. The recursive call, is where we use the same algorithm to solve a simpler version of the problem. The base case is the solution to the "simplest" possible problem For example, the base case in the problem 'find the largest number in a list' would be if the list had only one number Adding three numbers is equivalent to adding the first two numbers, and then adding these two numbers again.

Note, in Matlab, a function can be called without all the arguments. The nargin function tells the computer how many values were specified. This reduces the number of parameters nargin sent in to the function from 3 to 2, and 2 is the base case!

In a recursive algorithm, the computer "remembers" every previous state of the problem. This information is "held" by the computer on the "activation stack" i. Consider a rectangle grid of rooms, where each room may or may not have doors on the North, South, East, and West sides.

How do you find your way out of a maze? Here is one possible "algorithm" for finding the answer:. The "trick" here is of course, how do we know if the door leads to a room that leads to the exit? The answer is we don't but we can let the computer figure it out for us. What is the recursive part about the above algorithm? Its the "door leads out of the maze".

I didn't use Fibonacci as an example because I believe that it is not a good example for teaching recursion and recursion is one of the worst solutions to solve Fibonacci in terms of both time and space. View this article Fibonacci without recursiveness in Python - a better way. Nice post. Very interesting example with hello world being printed before the i value.

It almost looks like a recursive decorator. Recursion can be our best friend in many cases. But honestly, I am not sure that is best using recursion when iteration would work. I've run into some examples where recursion is needed and others where iteration is just best. What do you think? I wrote once about Fibonacci with iteration and flat a list with recursion.

Let me know your thoughts on it. I mean, that only applies to poorly designed languages, so it's not something to really worry about. There is typo about LIFO for stack principal. That was informative and everything but I still hate recursive functions! Good job keep the good work. Please tell me what is the alien thing about it.. I'm willing to write another article if it will help.

You can avoid the stack becoming full for long running recursive functions using trampolining. You all might like this post too! This dev-to-uploads. Thanh Van - Nov 4.

Bhavyashah - Nov 4. Ayobami Ogundiran - Nov 9. Lambda Technology Inc - Nov 4. DEV Community is a community of , amazing developers We're a place where coders share, stay up-to-date and grow their careers. Create account Log in. Twitter Facebook Github Instagram Twitch. Hello Engineers Today, I will talk about recursion in what, why, and how. Shall we start? What is recursion?



0コメント

  • 1000 / 1000