Recursion is a programming technique in which a method calls itself to solve a problem by breaking it
into smaller subproblems.
A recursive method must have two essential parts:
i. Base case – a condition that stops the recursion.
ii. Recursive case – the part where the method calls itself with a reduced or simpler input.
Recursion is commonly used for problems like factorial calculation, Fibonacci series, tree traversal
etc.
The recursion makes code short and readable. But, excessive recursion may lead to stack overflow
due to repeated method calls.
// Recursion example - Factorial value
class Factorial {
int fact(int n) {
int result;
if(n==1)
return 1;
result = n * fact(n-1) ;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}