Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is recursion [duplicate]

Tags:

java

recursion

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 ?

like image 599
Ralph Avatar asked Nov 28 '22 05:11

Ralph


1 Answers

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).

like image 184
Oded Avatar answered Dec 05 '22 18:12

Oded