Possible Duplicate:
Examples of Recursive functions
I have been trying to research recursion in programming as a concept (though I am specifically studying Java) and this is what I got to understand the best:
In real life for example, recursion is when we put two mirrors infront of each other and the images produced between them are recursive.
But I don't get this algorithm in programming? Can someone give me a simplified example to understand recursion ?
Recursion is a programming technique where a method can call itself as part of its calculation (sometimes you can have more than one method - the methods would then normally call each other circularly).
A popular example is calculating Fibonacci numbers:
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
The two basic components are a base case (n<=1
in the example) and the recursive case.
When creating a recursive algorithm you need to consider the base case and how, using the recursive case you will get to the base case (otherwise you end up with infinite recursion and blow the stack).
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