Possible Duplicates:
Real-world examples of recursion
Examples of Recursive functions
I see that most programming language tutorial teach recursion by using a simple example which is how to generate fibonacci sequence, my question is, is there another good example other than generating fibonacci sequence to explain how recursion works?
A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .
Different types of the recursionDirect Recursion. Indirect Recursion. Tail Recursion.
Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion.
Problems like finding Factorial of a number, Nth Fibonacci number and Length of a string can be solved using recursion.
The classic is the binary tree search:
def findval (node,val): if node == null: return null if node.val = val: return node if node.val > val: return findval (node.left,val) return findval (node.right,val) findval (root,thing_to_find)
That may be a little more complex than a simple formula but it's the "bread and butter" use of recursion, and it illustrates the best places to use it, that where the recursion levels are minimised.
By that I mean: you could add two non-negative numbers with:
def add (a,b): if b == 0: return a return add (a+1,b-1)
but you'd find yourself running out of stack space pretty quickly for large numbers (unless the compiler optimised tail-end recursions of course, but you should probably ignore that for the level of teaching you're concerned with).
The other answers mention various algorithms, which is completely fine, but if you want a bit more "concrete" example, you could list all files in some directory and its subdirectories. The hierarchical file system is a well-known example of a recursive (tree) structure, and you could show depth-first and breadth-first search using this concrete example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With