<p>One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion.</p>

<p>So the question is:</p>

<ol>
<li>What is recursion?</li>
<li>When would I use recursion?</li>
<li>Why don't people use recursion?</li>
</ol>

[{'answer_id': 3025, 'author': 'Louis Brandy', 'author_id': 2089740, 'author_profile': 'https://Stackoverflow.com/users/2089740', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>A function that calls itself</li>\n<li>When a function can be (easily) decomposed into a simple operation plus the same function on some smaller portion of the problem. I should say, rather, that this makes it a good candidate for recursion.</li>\n<li>They do!</li>\n</ol>\n\n<p>The canonical example is the factorial which looks like:</p>\n\n<pre><code>int fact(int a) \n{\n  if(a==1)\n    return 1;\n\n  return a*fact(a-1);\n}\n</code></pre>\n\n<p>In general, recursion isn't necessarily fast (function call overhead tends to be high because recursive functions tend to be small, see above) and can suffer from some problems (stack overflow anyone?). Some say they tend to be hard to get 'right' in non-trivial cases but I don't really buy into that. In some situations, recursion makes the most sense and is the most elegant and clear way to write a particular function. It should be noted that some languages favor recursive solutions and optimize them much more (LISP comes to mind).</p>\n"}, {'answer_id': 3030, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 3, 'selected': False, 'text': '<p>A recursive function is one which calls itself. The most common reason I\'ve found to use it is traversing a tree structure. For example, if I have a TreeView with checkboxes (think installation of a new program, "choose features to install" page), I might want a "check all" button which would be something like this (pseudocode):</p>\n\n<pre><code>function cmdCheckAllClick {\n    checkRecursively(TreeView1.RootNode);\n}\n\nfunction checkRecursively(Node n) {\n    n.Checked = True;\n    foreach ( n.Children as child ) {\n        checkRecursively(child);\n    }\n}\n</code></pre>\n\n<p>So you can see that the checkRecursively first checks the node which it is passed, then calls itself for each of that node\'s children.</p>\n\n<p>You do need to be a bit careful with recursion. If you get into an infinite recursive loop, you will get a Stack Overflow exception :)</p>\n\n<p>I can\'t think of a reason why people shouldn\'t use it, when appropriate. It is useful in some circumstances, and not in others.</p>\n\n<p>I think that because it\'s an interesting technique, some coders perhaps end up using it more often than they should, without real justification. This has given recursion a bad name in some circles.</p>\n'}, {'answer_id': 3035, 'author': 'Mike Minutillo', 'author_id': 358, 'author_profile': 'https://Stackoverflow.com/users/358', 'pm_score': 5, 'selected': False, 'text': "<p>Recursion is a method of solving problems based on the divide and conquer mentality.\nThe basic idea is that you take the original problem and divide it into smaller (more easily solved) instances of itself, solve those smaller instances (usually by using the same algorithm again) and then reassemble them into the final solution. </p>\n\n<p>The canonical example is a routine to generate the Factorial of n. The Factorial of n is calculated by multiplying all of the numbers between 1 and n. An iterative solution in C# looks like this:</p>\n\n<pre><code>public int Fact(int n)\n{\n  int fact = 1;\n\n  for( int i = 2; i &lt;= n; i++)\n  {\n    fact = fact * i;\n  }\n\n  return fact;\n}\n</code></pre>\n\n<p>There's nothing surprising about the iterative solution and it should make sense to anyone familiar with C#.</p>\n\n<p>The recursive solution is found by recognising that the nth Factorial is n * Fact(n-1). Or to put it another way, if you know what a particular Factorial number is you can calculate the next one. Here is the recursive solution in C#:</p>\n\n<pre><code>public int FactRec(int n)\n{\n  if( n &lt; 2 )\n  {\n    return 1;\n  }\n\n  return n * FactRec( n - 1 );\n}\n</code></pre>\n\n<p>The first part of this function is known as a <strong>Base Case</strong> (or sometimes Guard Clause) and is what prevents the algorithm from running forever. It just returns the value 1 whenever the function is called with a value of 1 or less. The second part is more interesting and is known as the <strong>Recursive Step</strong>. Here we call the same method with a slightly modified parameter (we decrement it by 1) and then multiply the result with our copy of n.</p>\n\n<p>When first encountered this can be kind of confusing so it's instructive to examine how it works when run. Imagine that we call FactRec(5). We enter the routine, are not picked up by the base case and so we end up like this:</p>\n\n<pre><code>// In FactRec(5)\nreturn 5 * FactRec( 5 - 1 );\n\n// which is\nreturn 5 * FactRec(4);\n</code></pre>\n\n<p>If we re-enter the method with the parameter 4 we are again not stopped by the guard clause and so we end up at:</p>\n\n<pre><code>// In FactRec(4)\nreturn 4 * FactRec(3);\n</code></pre>\n\n<p>If we substitute this return value into the return value above we get</p>\n\n<pre><code>// In FactRec(5)\nreturn 5 * (4 * FactRec(3));\n</code></pre>\n\n<p>This should give you a clue as to how the final solution is arrived at so we'll fast track and show each step on the way down:</p>\n\n<pre><code>return 5 * (4 * FactRec(3));\nreturn 5 * (4 * (3 * FactRec(2)));\nreturn 5 * (4 * (3 * (2 * FactRec(1))));\nreturn 5 * (4 * (3 * (2 * (1))));\n</code></pre>\n\n<p>That final substitution happens when the base case is triggered. At this point we have a simple algrebraic formula to solve which equates directly to the definition of Factorials in the first place.</p>\n\n<p>It's instructive to note that every call into the method results in either a base case being triggered or a call to the same method where the parameters are closer to a base case (often called a recursive call). If this is not the case then the method will run forever.</p>\n"}, {'answer_id': 3037, 'author': 'Mario Marinato', 'author_id': 431, 'author_profile': 'https://Stackoverflow.com/users/431', 'pm_score': 0, 'selected': False, 'text': '<p>I have created a recursive function to concatenate a list of strings with a separator between them.  I use it mostly to create SQL expressions, by passing a list of fields as the \'<em>items</em>\' and a \'<em>comma+space</em>\' as the separator.  Here\'s the function (It uses some Borland Builder native data types, but can be adapted to fit any other environment):</p>\n\n<pre><code>String ArrangeString(TStringList* items, int position, String separator)\n{\n  String result;\n\n  result = items-&gt;Strings[position];\n\n  if (position &lt;= items-&gt;Count)\n    result += separator + ArrangeString(items, position + 1, separator);\n\n  return result;\n}\n</code></pre>\n\n<p>I call it this way:</p>\n\n<pre><code>String columnsList;\ncolumnsList = ArrangeString(columns, 0, ", ");\n</code></pre>\n\n<p>Imagine you have an array named \'<em>fields</em>\' with this data inside it:  \'<em>albumName</em>\', \'<em>releaseDate</em>\', \'<em>labelId</em>\'.  Then you call the function:</p>\n\n<pre><code>ArrangeString(fields, 0, ", ");\n</code></pre>\n\n<p>As the function starts to work, the variable \'<em>result</em>\' receives the value of the position 0 of the array, which is \'<em>albumName</em>\'.</p>\n\n<p>Then it checks if the position it\'s dealing with is the last one.  As it isn\'t, then it concatenates the result with the separator and the result of a function, which, oh God, is this same function.  But this time, check it out, it call itself adding 1 to the position.</p>\n\n<pre><code>ArrangeString(fields, 1, ", ");\n</code></pre>\n\n<p>It keeps repeating, creating a LIFO pile, until it reaches a point where the position being dealt with IS the last one, so the function returns only the item on that position on the list, not concatenating anymore.  Then the pile is concatenated backwards.</p>\n\n<p>Got it?  If you don\'t, I have another way to explain it.  :o)</p>\n'}, {'answer_id': 3042, 'author': 'Joey deVilla', 'author_id': 216, 'author_profile': 'https://Stackoverflow.com/users/216', 'pm_score': 2, 'selected': False, 'text': '<p>Recursion works best with what I like to call "fractal problems", where you\'re dealing with a big thing that\'s made of smaller versions of that big thing, each of which is an even smaller version of the big thing, and so on. If you ever have to traverse or search through something like a tree or nested identical structures, you\'ve got a problem that might be a good candidate for recursion.</p>\n\n<p>People avoid recursion for a number of reasons:</p>\n\n<ol>\n<li><p>Most people (myself included) cut their programming teeth on procedural or object-oriented programming as opposed to functional programming. To such people, the iterative approach (typically using loops) feels more natural.</p></li>\n<li><p>Those of us who cut our programming teeth on procedural or object-oriented programming have often been told to avoid recursion because it\'s error prone.</p></li>\n<li><p>We\'re often told that recursion is slow. Calling and returning from a routine repeatedly involves a lot of stack pushing and popping, which is slower than looping. I think some languages handle this better than others, and those languages are most likely not those where the dominant paradigm is procedural or object-oriented.</p></li>\n<li><p>For at least a couple of programming languages I\'ve used, I remember hearing recommendations not to use recursion if it gets beyond a certain depth because its stack isn\'t that deep.</p></li>\n</ol>\n'}, {'answer_id': 3043, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a simple example: how many elements in a set.  (there are better ways to count things, but this is a nice simple recursive example.)</p>\n\n<p>First, we need two rules:</p>\n\n<ol>\n<li>if the set is empty, the count of items in the set is zero (duh!).</li>\n<li>if the set is not empty, the count is one plus the number of items in the set after one item is removed.</li>\n</ol>\n\n<p>Suppose you have a set like this: [x x x].  let\'s count how many items there are.</p>\n\n<ol>\n<li>the set is [x x x] which is not empty, so we apply rule 2.  the number of items is one plus the number of items in [x x] (i.e. we removed an item).</li>\n<li>the set is [x x], so we apply rule 2 again:  one + number of items in [x].</li>\n<li>the set is [x], which still matches rule 2:  one + number of items in [].</li>\n<li>Now the set is [], which matches rule 1: the count is zero!</li>\n<li>Now that we know the answer in step 4 (0), we can solve step 3 (1 + 0)</li>\n<li>Likewise, now that we know the answer in step 3 (1), we can solve step 2 (1 + 1)</li>\n<li>And finally now that we know the answer in step 2 (2), we can solve step 1 (1 + 2) and get the count of items in [x x x], which is 3.  Hooray!</li>\n</ol>\n\n<p>We can represent this as:</p>\n\n<pre><code>count of [x x x] = 1 + count of [x x]\n                 = 1 + (1 + count of [x])\n                 = 1 + (1 + (1 + count of []))\n                 = 1 + (1 + (1 + 0)))\n                 = 1 + (1 + (1))\n                 = 1 + (2)\n                 = 3\n</code></pre>\n\n<p>When applying a recursive solution, you usually have at least 2 rules:</p>\n\n<ul>\n<li>the basis, the simple case which states what happens when you have "used up" all of your data. This is usually some variation of "if you are out of data to process, your answer is X"</li>\n<li>the recursive rule, which states what happens if you still have data. This is usually some kind of rule that says "do something to make your data set smaller, and reapply your rules to the smaller data set."</li>\n</ul>\n\n<p>If we translate the above to pseudocode, we get:</p>\n\n<pre><code>numberOfItems(set)\n    if set is empty\n        return 0\n    else\n        remove 1 item from set\n        return 1 + numberOfItems(set)\n</code></pre>\n\n<p>There\'s a lot more useful examples (traversing a tree, for example) which I\'m sure other people will cover.</p>\n'}, {'answer_id': 3044, 'author': 'Kevin', 'author_id': 40, 'author_profile': 'https://Stackoverflow.com/users/40', 'pm_score': 0, 'selected': False, 'text': "<p>I use recursion.  What does that have to do with having a CS degree... (which I don't, by the way)</p>\n\n<p>Common uses I have found:</p>\n\n<ol>\n<li><strong>sitemaps</strong> - recurse through filesystem starting at document root</li>\n<li><strong>spiders</strong> - crawling through a website to find email address, links, etc.</li>\n<li>?</li>\n</ol>\n"}, {'answer_id': 3050, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 0, 'selected': False, 'text': "<p>Mario, I don't understand why you used recursion for that example.. Why not simply loop through each entry? Something like this:</p>\n\n<pre><code>String ArrangeString(TStringList* items, String separator)\n{\n    String result = items-&gt;Strings[0];\n\n    for (int position=1; position &lt; items-&gt;count; position++) {\n        result += separator + items-&gt;Strings[position];\n    }\n\n    return result;\n}\n</code></pre>\n\n<p>The above method would be faster, and is simpler. There's no need to use recursion in place of a simple loop. I think these sorts of examples is why recursion gets a bad rap. Even the canonical factorial function example is better implemented with a loop.</p>\n"}, {'answer_id': 3056, 'author': 'Peter Burns', 'author_id': 101, 'author_profile': 'https://Stackoverflow.com/users/101', 'pm_score': 2, 'selected': False, 'text': "<p>To recurse on a solved problem: do nothing, you're done.<br>\nTo recurse on an open problem: do the next step, then recurse on the rest.</p>\n"}, {'answer_id': 3093, 'author': 'Peter Burns', 'author_id': 101, 'author_profile': 'https://Stackoverflow.com/users/101', 'pm_score': 6, 'selected': False, 'text': '<p>There are a number of good explanations of <a href="http://en.wikipedia.org/wiki/Recursion_%28computer_science%29" rel="noreferrer">recursion</a> in this thread, this answer is about why you shouldn\'t use it in most languages.*  In the majority of major imperative language implementations (i.e. every major implementation of C, C++, Basic, Python, Ruby,Java, and C#) <a href="http://en.wikipedia.org/wiki/Iteration" rel="noreferrer">iteration</a> is vastly preferable to recursion.</p>\n\n<p>To see why, walk through the steps that the above languages use to call a function:</p>\n\n<ol>\n<li>space is carved out on <a href="http://en.wikipedia.org/wiki/Call_stack" rel="noreferrer">the stack</a> for the function\'s arguments and local variables</li>\n<li>the function\'s arguments are copied into this new space</li>\n<li>control jumps to the function</li>\n<li><strong><em>the function\'s code runs</em></strong></li>\n<li>the function\'s result is copied into a return value</li>\n<li>the stack is rewound to its previous position</li>\n<li>control jumps back to where the function was called</li>\n</ol>\n\n<p>Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop.  However, the real problem is in step #1.  When many programs start, they allocate a single chunk of memory for their stack, and when they run out of that memory (often, but not always due to recursion), the program crashes due to a <a href="http://en.wikipedia.org/wiki/Stack_overflow" rel="noreferrer">stack overflow</a>.</p>\n\n<p>So in these languages recursion is slower and it makes you vulnerable to crashing.  There are still some arguments for using it though.  In general, code written recursively is shorter and a bit more elegant, once you know how to read it.</p>\n\n<p>There is a technique that language implementers can use called <a href="http://en.wikipedia.org/wiki/Tail_call_optimization" rel="noreferrer">tail call optimization</a> which can eliminate some classes of stack overflow.  Put succinctly: if a function\'s return expression is simply the result of a function call, then you don\'t need to add a new level onto the stack, you can reuse the current one for the function being called.  Regrettably, few imperative language-implementations have tail-call optimization built in. </p>\n\n<p>* <em>I love recursion.  <a href="http://www.haskell.org/" rel="noreferrer">My favorite static language</a> doesn\'t use loops at all, recursion is the only way to do something repeatedly. I just don\'t think that recursion is generally a good idea in languages that aren\'t tuned for it.</em></p>\n\n<p>** By the way Mario, the typical name for your ArrangeString function is "join", and I\'d be surprised if your language of choice doesn\'t already have an implementation of it.</p>\n'}, {'answer_id': 19839, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 1, 'selected': False, 'text': '<p>You want to use it anytime you have a tree structure.  It is very useful in reading XML.</p>\n'}, {'answer_id': 19918, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 0, 'selected': False, 'text': '<p>Actually the better recursive solution for factorial should be:</p>\n\n<pre><code>int factorial_accumulate(int n, int accum) {\n    return (n &lt; 2 ? accum : factorial_accumulate(n - 1, n * accum));\n}\n\nint factorial(int n) {\n    return factorial_accumulate(n, 1);\n}\n</code></pre>\n\n<p>Because this version is <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="nofollow noreferrer">Tail Recursive</a> </p>\n'}, {'answer_id': 2764802, 'author': 'Andreas Brinck', 'author_id': 125672, 'author_profile': 'https://Stackoverflow.com/users/125672', 'pm_score': 6, 'selected': False, 'text': '<p>In the most basic computer science sense, recursion is a function that calls itself. Say you have a linked list structure:</p>\n\n<pre><code>struct Node {\n    Node* next;\n};\n</code></pre>\n\n<p>And you want to find out how long a linked list is you can do this with recursion:</p>\n\n<pre><code>int length(const Node* list) {\n    if (!list-&gt;next) {\n        return 1;\n    } else {\n        return 1 + length(list-&gt;next);\n    }\n}\n</code></pre>\n\n<p>(This could of course be done with a for loop as well, but is useful as an illustration of the concept)</p>\n'}, {'answer_id': 2764807, 'author': 'bennybdbc', 'author_id': 178810, 'author_profile': 'https://Stackoverflow.com/users/178810', 'pm_score': 1, 'selected': False, 'text': '<p>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. </p>\n'}, {'answer_id': 2764809, 'author': 'Amber', 'author_id': 148870, 'author_profile': 'https://Stackoverflow.com/users/148870', 'pm_score': 3, 'selected': False, 'text': '<p>Recursion refers to a method which solves a problem by solving a smaller version of the problem and then using that result plus some other computation to formulate the answer to the original problem. Often times, in the process of solving the smaller version, the method will solve a yet smaller version of the problem, and so on, until it reaches a "base case" which is trivial to solve.</p>\n\n<p>For instance, to calculate a factorial for the number <code>X</code>, one can represent it as <code>X times the factorial of X-1</code>. Thus, the method "recurses" to find the factorial of <code>X-1</code>, and then multiplies whatever it got by <code>X</code> to give a final answer. Of course, to find the factorial of <code>X-1</code>, it\'ll first calculate the factorial of <code>X-2</code>, and so on. The base case would be when <code>X</code> is 0 or 1, in which case it knows to return <code>1</code> since <code>0! = 1! = 1</code>.</p>\n'}, {'answer_id': 2764818, 'author': 'Dave Markle', 'author_id': 24995, 'author_profile': 'https://Stackoverflow.com/users/24995', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 2764835, 'author': 'Robben_Ford_Fan_boy', 'author_id': 227426, 'author_profile': 'https://Stackoverflow.com/users/227426', 'pm_score': 2, 'selected': False, 'text': "<p>I like this definition:<br />\nIn recursion, a routine solves a small part of a problem itself, divides the problem into smaller pieces, and then calls itself to solve each of the smaller pieces.</p>\n<p>I also like Steve McConnells discussion of recursion in Code Complete where he criticises the examples used in Computer Science books on Recursion.</p>\n<blockquote>\n<h3>Don't use recursion for factorials or Fibonacci numbers</h3>\n<p>One problem with\ncomputer-science textbooks is that\nthey present silly examples of\nrecursion. The typical examples are\ncomputing a factorial or computing a\nFibonacci sequence. Recursion is a\npowerful tool, and it's really dumb to\nuse it in either of those cases. If a\nprogrammer who worked for me used\nrecursion to compute a factorial, I'd\nhire someone else.</p>\n</blockquote>\n<p>I thought this was a very interesting point to raise and may be a reason why recursion is often misunderstood.</p>\n<p>EDIT:\nThis was not a dig at Dav's answer - I had not seen that reply when I posted this</p>\n"}, {'answer_id': 2764836, 'author': 'RationalGeek', 'author_id': 123468, 'author_profile': 'https://Stackoverflow.com/users/123468', 'pm_score': 4, 'selected': False, 'text': '<p>Recursion is solving a problem with a function that calls itself.  A good example of this is a factorial function.  Factorial is a math problem where factorial of 5, for example, is 5 * 4 * 3 * 2 * 1.  This function solves this in C# for positive integers (not tested - there may be a bug).</p>\n\n<pre><code>public int Factorial(int n)\n{\n    if (n &lt;= 1)\n        return 1;\n\n    return n * Factorial(n - 1);\n}\n</code></pre>\n'}, {'answer_id': 2765008, 'author': 'Andres Jaan Tack', 'author_id': 1288364, 'author_profile': 'https://Stackoverflow.com/users/1288364', 'pm_score': 1, 'selected': False, 'text': '<p><em>"If I have a hammer, make everything look like a nail."</em></p>\n\n<p>Recursion is a problem-solving strategy for <em>huge</em> problems, where at every step just, "turn 2 small things into one bigger thing," each time with the same hammer.</p>\n\n<h2>Example</h2>\n\n<p>Suppose your desk is covered with a disorganized mess of 1024 papers. How do you make one neat, clean stack of papers from the mess, using recursion?</p>\n\n<ol>\n<li><strong>Divide:</strong> Spread all the sheets out, so you have just one sheet in each "stack".</li>\n<li><strong>Conquer:</strong>\n\n<ol start="2">\n<li>Go around, putting each sheet on top of one other sheet. You now have stacks of 2.</li>\n<li>Go around, putting each 2-stack on top of another 2-stack. You now have stacks of 4.</li>\n<li>Go around, putting each 4-stack on top of another 4-stack. You now have stacks of 8.</li>\n<li>... on and on ...</li>\n<li>You now have one huge stack of 1024 sheets!</li>\n</ol></li>\n</ol>\n\n<p>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.</p>\n'}, {'answer_id': 2765030, 'author': 'Konstantin Spirin', 'author_id': 1423922, 'author_profile': 'https://Stackoverflow.com/users/1423922', 'pm_score': 3, 'selected': False, 'text': '<p>Recursion is an expression directly or indirectly referencing itself.</p>\n\n<p>Consider recursive acronyms as a simple example:</p>\n\n<ul>\n<li><strong>GNU</strong> stands for <strong>GNU\'s Not Unix</strong></li>\n<li><strong>PHP</strong> stands for <strong>PHP: Hypertext Preprocessor</strong></li>\n<li><strong>YAML</strong> stands for <strong>YAML Ain\'t Markup Language</strong></li>\n<li><strong>WINE</strong> stands for <strong>Wine Is Not an Emulator</strong></li>\n<li><strong>VISA</strong> stands for <strong>Visa International Service Association</strong></li>\n</ul>\n\n<p><a href="http://en.wikipedia.org/wiki/Recursive_acronym" rel="nofollow noreferrer">More examples on Wikipedia</a></p>\n'}, {'answer_id': 2765055, 'author': 'kacalapy', 'author_id': 352157, 'author_profile': 'https://Stackoverflow.com/users/352157', 'pm_score': 1, 'selected': False, 'text': '<p>its a way to do things over and over indefinitely such that every option is used. </p>\n\n<p>for example if you wanted to get all the links on an html page you will want to have recursions because when you get all the links on page 1 you will want to get all the links on each of the links found on the first page. then for each link to a newpage you will want those links and so on... in other words it is a function that calls itself from inside itself.</p>\n\n<p>when you do this you need a way to know when to stop or else you will be in an endless loop so you add an integer param to the function to track the number of cycles.</p>\n\n<p>in c# you will have something like this:</p>\n\n<pre><code>private void findlinks(string URL, int reccursiveCycleNumb)    {\n   if (reccursiveCycleNumb == 0)\n        {\n            return;\n        }\n\n        //recursive action here\n        foreach (LinkItem i in LinkFinder.Find(URL))\n        {\n            //see what links are being caught...\n            lblResults.Text += i.Href + "&lt;BR&gt;";\n\n            findlinks(i.Href, reccursiveCycleNumb - 1);\n        }\n\n        reccursiveCycleNumb -= reccursiveCycleNumb;\n}\n</code></pre>\n'}, {'answer_id': 2765307, 'author': 'Shivam', 'author_id': 234810, 'author_profile': 'https://Stackoverflow.com/users/234810', 'pm_score': 1, 'selected': False, 'text': '<p>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.e. stop it from calling itself if a condition is met - this prevents the creating of an infinite loop. Not all functions are suited to be used recursively.</p>\n'}, {'answer_id': 2765346, 'author': 'Indigo Praveen', 'author_id': 317536, 'author_profile': 'https://Stackoverflow.com/users/317536', 'pm_score': 1, 'selected': False, 'text': '<p>In plain English, recursion means to repeat someting again and again.</p>\n\n<p>In programming one example is of calling the function within itself .</p>\n\n<p>Look on the following example of calculating factorial of a number: </p>\n\n<pre><code>public int fact(int n)\n{\n    if (n==0) return 1;\n    else return n*fact(n-1)\n}\n</code></pre>\n'}, {'answer_id': 2765354, 'author': 'Luka Ramishvili', 'author_id': 324220, 'author_profile': 'https://Stackoverflow.com/users/324220', 'pm_score': 1, 'selected': False, 'text': "<p>hey, sorry if my opinion agrees with someone, I'm just trying to explain recursion in plain english.</p>\n\n<p>suppose you have three managers - Jack, John and Morgan.\nJack manages 2 programmers, John - 3, and Morgan - 5.\nyou are going to give every manager 300$ and want to know what would it cost.\nThe answer is obvious - but what if 2 of Morgan-s employees are also managers?</p>\n\n<p>HERE comes the recursion.\nyou start from the top of the hierarchy. the summery cost is 0$. \nyou start with Jack,\nThen check if he has any managers as employees. if you find any of them are, check if they have any managers as employees and so on. Add 300$ to the summery cost every time you find a manager.\nwhen you are finished with Jack, go to John, his employees and then to Morgan.</p>\n\n<p>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.</p>\n\n<p>Recursion is a tree, with branches and leaves, called parents and children respectively.\nWhen you use a recursion algorithm, you more or less consciously are building a tree from the data.</p>\n"}, {'answer_id': 2765519, 'author': 'Bastiaan Linders', 'author_id': 255657, 'author_profile': 'https://Stackoverflow.com/users/255657', 'pm_score': 2, 'selected': False, 'text': '<p>In plain English:\nAssume you can do 3 things:</p>\n\n<ol>\n<li>Take one apple</li>\n<li>Write down tally marks</li>\n<li>Count tally marks</li>\n</ol>\n\n<p><strong>You have a lot of apples in front of you on a table and you want to know how many apples there are.</strong></p>\n\n<pre><code>start\n  Is the table empty?\n  yes: Count the tally marks and cheer like it\'s your birthday!\n  no:  Take 1 apple and put it aside\n       Write down a tally mark\n       goto start\n</code></pre>\n\n<p>The process of repeating the same thing till you are done is called recursion.</p>\n\n<p>I hope this is the "plain english" answer you are looking for!</p>\n'}, {'answer_id': 2765695, 'author': 'Gregory Brown', 'author_id': 289274, 'author_profile': 'https://Stackoverflow.com/users/289274', 'pm_score': 2, 'selected': False, 'text': '<p><strong>A recursive statement is one in which you define the process of what to do next as a combination of the inputs and what you have already done.</strong></p>\n\n<p>For example, take factorial:</p>\n\n<pre><code>factorial(6) = 6*5*4*3*2*1\n</code></pre>\n\n<p>But it\'s easy to see factorial(6) also is:</p>\n\n<pre><code>6 * factorial(5) = 6*(5*4*3*2*1).\n</code></pre>\n\n<p>So generally:</p>\n\n<pre><code>factorial(n) = n*factorial(n-1)\n</code></pre>\n\n<p>Of course, the tricky thing about recursion is that if you want to define things in terms of what you have already done, there needs to be some place to start.</p>\n\n<p>In this example, we just make a special case by defining factorial(1) = 1.</p>\n\n<p>Now we see it from the bottom up:</p>\n\n<pre><code>factorial(6) = 6*factorial(5)\n                   = 6*5*factorial(4)\n                   = 6*5*4*factorial(3) = 6*5*4*3*factorial(2) = 6*5*4*3*2*factorial(1) = 6*5*4*3*2*1\n</code></pre>\n\n<p>Since we defined factorial(1) = 1, we reach the "bottom".</p>\n\n<p>Generally speaking, recursive procedures have two parts:</p>\n\n<p>1) The recursive part, which defines some procedure in terms of new inputs combined with what you\'ve "already done" via the same procedure.  (i.e. <code>factorial(n) = n*factorial(n-1)</code>)</p>\n\n<p>2) A base part, which makes sure that the process doesn\'t repeat forever by giving it some place to start (i.e. <code>factorial(1) = 1</code>)</p>\n\n<p>It can be a bit confusing to get your head around at first, but just look at a bunch of examples and it should all come together.  If you want a much deeper understanding of the concept, study mathematical induction.  Also, be aware that some languages optimize for recursive calls while others do not.  It\'s pretty easy to make insanely slow recursive functions if you\'re not careful, but there are also techniques to make them performant in most cases.</p>\n\n<p>Hope this helps...</p>\n'}, {'answer_id': 2765712, 'author': 'Steve Wortham', 'author_id': 102896, 'author_profile': 'https://Stackoverflow.com/users/102896', 'pm_score': 6, 'selected': False, 'text': '<p>Whenever a function calls itself, creating a loop, then that\'s recursion.  As with anything there are good uses and bad uses for recursion.</p>\n\n<p>The most simple example is tail recursion where the very last line of the function is a call to itself:</p>\n\n<pre><code>int FloorByTen(int num)\n{\n    if (num % 10 == 0)\n        return num;\n    else\n        return FloorByTen(num-1);\n}\n</code></pre>\n\n<p>However, this is a lame, almost pointless example because it can easily be replaced by more efficient iteration.  After all, recursion suffers from function call overhead, which in the example above could be substantial compared to the operation inside the function itself.</p>\n\n<p>So the whole reason to do recursion rather than iteration should be to take advantage of the <a href="http://en.wikipedia.org/wiki/Call_stack" rel="noreferrer">call stack</a> to do some clever stuff.  For example, if you call a function multiple times with different parameters inside the same loop then that\'s a way to accomplish <a href="http://en.wikipedia.org/wiki/Branch_(computer_science)" rel="noreferrer">branching</a>.  A classic example is the <a href="http://en.wikipedia.org/wiki/Sierpinski_triangle" rel="noreferrer">Sierpinski triangle</a>.</p>\n\n<p><img src="https://i.stack.imgur.com/HAEZW.gif" alt="enter image description here"></p>\n\n<p>You can draw one of those very simply with recursion, where the call stack branches in 3 directions:</p>\n\n<pre><code>private void BuildVertices(double x, double y, double len)\n{\n    if (len &gt; 0.002)\n    {\n        mesh.Positions.Add(new Point3D(x, y + len, -len));\n        mesh.Positions.Add(new Point3D(x - len, y - len, -len));\n        mesh.Positions.Add(new Point3D(x + len, y - len, -len));\n        len *= 0.5;\n        BuildVertices(x, y + len, len);\n        BuildVertices(x - len, y - len, len);\n        BuildVertices(x + len, y - len, len);\n    }\n}\n</code></pre>\n\n<p>If you attempt to do the same thing with iteration I think you\'ll find it takes a lot more code to accomplish.  </p>\n\n<p>Other common use cases might include traversing hierarchies, e.g. website crawlers, directory comparisons, etc.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>In practical terms, recursion makes the most sense whenever you need iterative branching.</p>\n'}, {'answer_id': 2765731, 'author': 'Ralph', 'author_id': 280244, 'author_profile': 'https://Stackoverflow.com/users/280244', 'pm_score': 2, 'selected': False, 'text': '<p>An example: A recursive definition of a staircase is:\nA staircase consists of:\n- a single step and a staircase (recursion)\n- or only a single step (termination)</p>\n'}, {'answer_id': 2765870, 'author': 'mfx', 'author_id': 8015, 'author_profile': 'https://Stackoverflow.com/users/8015', 'pm_score': 1, 'selected': False, 'text': '<p>Any algorithm exhibits <em>structural</em> recursion on a datatype if basically consists of a switch-statement with a case for each case of the datatype.</p>\n\n<p>for example, when you are working on a type</p>\n\n<pre><code>  tree = null \n       | leaf(value:integer) \n       | node(left: tree, right:tree)\n</code></pre>\n\n<p>a structural recursive algorithm would have the form</p>\n\n<pre><code> function computeSomething(x : tree) =\n   if x is null: base case\n   if x is leaf: do something with x.value\n   if x is node: do something with x.left,\n                 do something with x.right,\n                 combine the results\n</code></pre>\n\n<p>this is really the most obvious way to write any algorith that works on a data structure.</p>\n\n<p>now, when you look at the integers (well, the natural numbers) as defined using the Peano axioms</p>\n\n<pre><code> integer = 0 | succ(integer)\n</code></pre>\n\n<p>you see that a structural recursive algorithm on integers looks like this</p>\n\n<pre><code> function computeSomething(x : integer) =\n   if x is 0 : base case\n   if x is succ(prev) : do something with prev\n</code></pre>\n\n<p>the too-well-known factorial function is about the most trivial example of\nthis form.</p>\n'}, {'answer_id': 2765912, 'author': 'Greg Bacon', 'author_id': 123109, 'author_profile': 'https://Stackoverflow.com/users/123109', 'pm_score': 3, 'selected': False, 'text': '<p>Consider an <a href="http://en.wikipedia.org/wiki/Greatest_common_divisor" rel="nofollow noreferrer">old, well known problem</a>:</p>\n\n<blockquote>\n  <p>In mathematics, the <strong>greatest common divisor</strong> (gcd) … of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder.</p>\n</blockquote>\n\n<p>The definition of gcd is surprisingly simple:</p>\n\n<p><img src="https://imgur.com/wUhAu.png" alt="gcd definition"></p>\n\n<p>where mod is the <a href="http://en.wikipedia.org/wiki/Modulo_operator" rel="nofollow noreferrer">modulo operator</a> (that is, the remainder after integer division).</p>\n\n<p>In English, this definition says the greatest common divisor of any number and zero is that number, and the greatest common divisor of two numbers <em>m</em> and <em>n</em> is the greatest common divisor of <em>n</em> and the remainder after dividing <em>m</em> by <em>n</em>.</p>\n\n<p>If you\'d like to know why this works, see the Wikipedia article on the <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm" rel="nofollow noreferrer">Euclidean algorithm</a>.</p>\n\n<p>Let\'s compute gcd(10, 8) as an example. Each step is equal to the one just before it:</p>\n\n<ol>\n<li>gcd(10, 8)</li>\n<li>gcd(10, 10 mod 8) </li>\n<li>gcd(8, 2)</li>\n<li>gcd(8, 8 mod 2)</li>\n<li>gcd(2, 0)</li>\n<li>2</li>\n</ol>\n\n<p>In the first step, 8 does not equal zero, so the second part of the definition applies. 10 mod 8 = 2 because 8 goes into 10 once with a remainder of 2. At step 3, the second part applies again, but this time 8 mod 2 = 0 because 2 divides 8 with no remainder. At step 5, the second argument is 0, so the answer is 2.</p>\n\n<p>Did you notice that gcd appears on both the left and right sides of the equals sign? A mathematician would say this definition is recursive because the expression you\'re defining <a href="http://www.google.com/search?sourceid=chrome&amp;ie=UTF-8&amp;q=define:recur" rel="nofollow noreferrer">recurs</a> inside its definition.</p>\n\n<p>Recursive definitions tend to be elegant. For example, a recursive definition for the sum of a list is</p>\n\n<pre><code>sum l =\n    if empty(l)\n        return 0\n    else\n        return head(l) + sum(tail(l))\n</code></pre>\n\n<p>where <code>head</code> is the first element in a list and <code>tail</code> is the rest of the list. Note that <code>sum</code> recurs inside its definition at the end.</p>\n\n<p>Maybe you\'d prefer the maximum value in a list instead:</p>\n\n<pre><code>max l =\n    if empty(l)\n        error\n    elsif length(l) = 1\n        return head(l)\n    else\n        tailmax = max(tail(l))\n        if head(l) &gt; tailmax\n            return head(l)\n        else\n            return tailmax\n</code></pre>\n\n<p>You might define multiplication of non-negative integers recursively to turn it into a series of additions:</p>\n\n<pre><code>a * b =\n    if b = 0\n        return 0\n    else\n        return a + (a * (b - 1))\n</code></pre>\n\n<p>If that bit about transforming multiplication into a series of additions doesn\'t make sense, try expanding a few simple examples to see how it works.</p>\n\n<p><a href="http://en.wikipedia.org/wiki/Merge_sort" rel="nofollow noreferrer">Merge sort</a> has a lovely recursive definition:</p>\n\n<pre><code>sort(l) =\n    if empty(l) or length(l) = 1\n        return l\n    else\n        (left,right) = split l\n        return merge(sort(left), sort(right))\n</code></pre>\n\n<p>Recursive definitions are all around if you know what to look for. Notice how all of these definitions have very simple base cases, <em>e.g.</em>, gcd(m, 0) = m. The recursive cases whittle away at the problem to get down to the easy answers.</p>\n\n<p>With this understanding, you can now appreciate the other algorithms in <a href="http://en.wikipedia.org/wiki/Recursion_(computer_science)" rel="nofollow noreferrer">Wikipedia\'s article on recursion</a>!</p>\n'}, {'answer_id': 2765921, 'author': 'Syed Tayyab Ali', 'author_id': 69111, 'author_profile': 'https://Stackoverflow.com/users/69111', 'pm_score': 1, 'selected': False, 'text': '<p>function call itself or use its own definition.</p>\n'}, {'answer_id': 2766028, 'author': 'Don Mackenzie', 'author_id': 100347, 'author_profile': 'https://Stackoverflow.com/users/100347', 'pm_score': 1, 'selected': False, 'text': '<p>Recursion in computing is a technique used to compute a result or side effect following the normal return from a single function (method, procedure or block) invocation. </p>\n\n<p>The recursive function, by definition must have the ability to invoke itself either directly or indirectly (through other functions) depending on an exit condition or conditions not being met. If an exit condition is met the particular invocation returns to it\'s caller. This continues until the initial invocation is returned from, at which time the desired result or side effect will be available.</p>\n\n<p>As an example, here\'s a function to perform the Quicksort algorithm in Scala (<a href="http://en.wikipedia.org/wiki/Scala_%28programming_language%29" rel="nofollow noreferrer">copied from the Wikipedia entry for Scala</a>)</p>\n\n<pre><code>def qsort: List[Int] =&gt; List[Int] = {\n  case Nil =&gt; Nil\n  case pivot :: tail =&gt;\n    val (smaller, rest) = tail.partition(_ &lt; pivot)\n    qsort(smaller) ::: pivot :: qsort(rest)\n}\n</code></pre>\n\n<p>In this case the exit condition is an empty list.</p>\n'}, {'answer_id': 2766604, 'author': 'J.K.Aery', 'author_id': 283163, 'author_profile': 'https://Stackoverflow.com/users/283163', 'pm_score': 1, 'selected': False, 'text': '<p>Recursion is technique of defining a function, a set or an algorithm in terms of itself.</p>\n\n<p>For example </p>\n\n<pre><code>n! = n(n-1)(n-2)(n-3)...........*3*2*1\n</code></pre>\n\n<p>Now it can be defined recursively as:-</p>\n\n<pre><code>n! = n(n-1)!   for n&gt;=1\n</code></pre>\n\n<p>In programming terms, when a function or method calls itself repeatedly, until some specific condition gets satisfied, this process is called Recursion. But there must be a terminating condition and function or method must no enter into an infinite loop.</p>\n'}, {'answer_id': 2766661, 'author': 'Donal Fellows', 'author_id': 301832, 'author_profile': 'https://Stackoverflow.com/users/301832', 'pm_score': 1, 'selected': False, 'text': '<p>A great many problems can be thought of in two types of pieces:</p>\n\n<ol>\n<li>Base cases, which are elementary things that you can solve by just looking at them, and</li>\n<li>Recursive cases, which build a bigger problem out of smaller pieces (elementary or otherwise).</li>\n</ol>\n\n<p>So what\'s a recursive function? Well, that\'s where you have a function that is defined in terms of itself, directly or indirectly. OK, that sounds ridiculous until you realize that it is sensible for the problems of the kind described above: you solve the base cases directly and deal with the recursive cases by using recursive calls to solve the smaller pieces of the problem embedded within.</p>\n\n<p>The truly classic example of where you need recursion (or something that smells very much like it) is when you\'re dealing with a tree. The leaves of the tree are the base case, and the branches are the recursive case. (In pseudo-C.)</p>\n\n<pre><code>struct Tree {\n    int leaf;\n    Tree *leftBranch;\n    Tree *rightBranch;\n};\n</code></pre>\n\n<p>The simplest way of printing this out in order is to use recursion:</p>\n\n<pre><code>function printTreeInOrder(Tree *tree) {\n    if (tree-&gt;leftBranch) {\n        printTreeInOrder(tree-&gt;leftBranch);\n    }\n    print(tree-&gt;leaf);\n    if (tree-&gt;rightBranch) {\n        printTreeInOrder(tree-&gt;rightBranch);\n    }\n}\n</code></pre>\n\n<p>It\'s dead easy to see that that\'s going to work, since it\'s crystal clear. (The non-recursive equivalent is quite a lot more complex, requiring a stack structure internally to manage the list of things to process.) Well, assuming that nobody\'s done a circular connection of course.</p>\n\n<p>Mathematically, the trick to showing that recursion is tamed is to focus on finding a metric for the size of the arguments. For our tree example, the easiest metric is the maximum depth of the tree below the current node. At leaves, it\'s zero. At a branch with only leaves below it, it\'s one, etc. Then you can simply show that there\'s strictly ordered sequence on the size of the arguments that the function is invoked on in order to process the tree; the arguments to the recursive calls are always "lesser" in the sense of the metric than the argument to the overall call. With a strictly decreasing cardinal metric, you\'re sorted.</p>\n\n<p>It\'s also possible to have infinite recursion. That\'s messy and in many languages won\'t work because the stack blows up. (Where it does work, the language engine must be determining that the function somehow doesn\'t return and is able therefore to optimize away the keeping of the stack. Tricky stuff in general; tail-recursion is just the most trivial way of doing this.)</p>\n'}, {'answer_id': 2766923, 'author': 'corsiKa', 'author_id': 330057, 'author_profile': 'https://Stackoverflow.com/users/330057', 'pm_score': 1, 'selected': False, 'text': '<p>Recursion is when you have an operation that uses itself. It probably will have a stopping point, otherwise it would go on forever.</p>\n\n<p>Let\'s say you want to look up a word in the dictionary. You have an operation called "look-up" at your disposal.</p>\n\n<p>Your friend says "I could really spoon up some pudding right now!" You don\'t know what he means, so you look up "spoon" in the dictionary, and it reads something like this:</p>\n\n<p>Spoon: noun - a utensil with a round scoop at the end.\nSpoon: verb - to use a spoon on something\nSpoon: verb - to cuddle closely from behind</p>\n\n<p>Now, being that you\'re really not good with English, this points you in the right direction, but you need more info. So you select "utensil" and "cuddle" to look up for some more information.</p>\n\n<p>Cuddle: verb - to snuggle\nUtensil: noun - a tool, often an eating utensil</p>\n\n<p>Hey! You know what snuggling is, and it has nothing to do with pudding. You also know that pudding is something you eat, so it makes sense now. Your friend must want to eat pudding with a spoon.</p>\n\n<p>Okay, okay, this was a very lame example, but it illustrates (perhaps poorly) the two main parts of recursion.\n1) It uses itself. In this example, you haven\'t really looked up a word meaningfully until you understand it, and that might mean looking up more words. This brings us to point two,\n2) It stops somewhere. It has to have some kind of base-case. Otherwise, you\'d just end up looking up every word in the dictionary, which probably isn\'t too useful. Our base-case was that you got enough information to make a connection between what you previously did and did not understand.</p>\n\n<p>The traditional example that\'s given is factorial, where 5 factorial is 1*2*3*4*5 (which is 120). The base case would be 0 (or 1, depending). So, for any whole number n, you do the following</p>\n\n<p>is n equal to 0? return 1\notherwise, return n * (factorial of n-1)</p>\n\n<p>let\'s do this with the example of 4 (which we know ahead of time is 1*2*3*4 = 24).</p>\n\n<p>factorial of 4 ... is it 0? no, so it must be 4 * factorial of 3\nbut what\'s factorial of 3? it\'s 3 * factorial of 2\nfactorial of 2 is 2 * factorial of 1\nfactorial of 1 is 1 * factorial of 0\nand we KNOW factorial of 0! :-D it\'s 1, that\'s the definition\nfactorial of 1 is 1 * factorial of 0, which was 1... so 1*1 = 1\nfactorial of 2 is 2 * factorial of 1, which was 1... so 2*1 = 2\nfactorial of 3 is 3 * factorial of 2, which was 2... so 3*2 = 6\nfactorial of 4 (finally!!) is 4 * factorial of 3, which was 6... 4*6 is 24</p>\n\n<p>Factorial is a simple case of "base case, and uses itself".</p>\n\n<p>Now, notice we were still working on factorial of 4 the entire way down... If we wanted factorial of 100, we\'d have to go all the way down to 0... which might have a lot of overhead to it. In the same manner, if we find an obscure word to look up in the dictionary, it might take looking up other words and scanning for context clues until we find a connection we\'re familiar with. Recursive methods can take a long time to work their way through. However, when they\'re used correctly, and understood, they can make complicated work surprisingly simple.</p>\n'}, {'answer_id': 2766968, 'author': 'Dima', 'author_id': 13313, 'author_profile': 'https://Stackoverflow.com/users/13313', 'pm_score': 1, 'selected': False, 'text': '<p>The simplest definition of recursion is "self-reference".  A function that refers to itself, i. e. calls itself is recursive.  The most important thing to keep in mind, is that a recursive function must have a "base case", i. e. a condition that if true causes it not to call itself, and thus terminate the recursion.  Otherwise you will have infinite recursion:</p>\n\n<p><a href="http://cart.kolix.de/wp-content/uploads/2009/12/infinite-recursion.jpg" rel="nofollow noreferrer">recursion http://cart.kolix.de/wp-content/uploads/2009/12/infinite-recursion.jpg</a></p>\n'}, {'answer_id': 2767157, 'author': 'DMin', 'author_id': 237351, 'author_profile': 'https://Stackoverflow.com/users/237351', 'pm_score': 6, 'selected': False, 'text': "<p>Simple english example of recursion.</p>\n\n<pre><code>A child couldn't sleep, so her mother told her a story about a little frog,\n    who couldn't sleep, so the frog's mother told her a story about a little bear,\n         who couldn't sleep, so the bear's mother told her a story about a little weasel... \n            who fell asleep.\n         ...and the little bear fell asleep;\n    ...and the little frog fell asleep;\n...and the child fell asleep.\n</code></pre>\n"}, {'answer_id': 2767218, 'author': 'mcdon', 'author_id': 135280, 'author_profile': 'https://Stackoverflow.com/users/135280', 'pm_score': 2, 'selected': False, 'text': '<p>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.  The key part of a recursive item is that it contains an instance/call of itself.</p>\n\n<p>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.</p>\n\n<p>A <a href="http://en.wikipedia.org/wiki/Binary_search_tree" rel="nofollow noreferrer">binary search tree</a> 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.</p>\n'}, {'answer_id': 22321942, 'author': 'AlienOnEarth', 'author_id': 2041115, 'author_profile': 'https://Stackoverflow.com/users/2041115', 'pm_score': 2, 'selected': False, 'text': '<p>1.) \nA method is recursive if it can call itself; either directly:</p>\n\n<pre><code>void f() {\n   ... f() ... \n}\n</code></pre>\n\n<p>or indirectly:</p>\n\n<pre><code>void f() {\n    ... g() ...\n}\n\nvoid g() {\n   ... f() ...\n}\n</code></pre>\n\n<p>2.) When to use recursion</p>\n\n<pre><code>Q: Does using recursion usually make your code faster? \nA: No.\nQ: Does using recursion usually use less memory? \nA: No.\nQ: Then why use recursion? \nA: It sometimes makes your code much simpler!\n</code></pre>\n\n<p>3.) 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.</p>\n'}, {'answer_id': 25581243, 'author': 'fajrian', 'author_id': 592427, 'author_profile': 'https://Stackoverflow.com/users/592427', 'pm_score': 2, 'selected': False, 'text': "<p>This is an old question, but I want to add an answer from logistical point of view (i.e not from algorithm correctness point of view or performance point of view).</p>\n\n<p>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).</p>\n\n<p>Thus, I often avoid recursion, and use stack operation instead, because recursion itself is essentially a stack operation.</p>\n"}]
['https://Stackoverflow.com/questions/3021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358/']