Java Recursion
One does not simply understand RECURSION without understanding RECURSION.
In programming, recursion is a technique through which a function calls itself. With the help of recursion, we can break down complex problems into simple problems.
Example: Factorial of a number'
//factorial(n) = n*factorial(n-1) [n >= 1]
Now, let's see an example to see the beauty of recursion in programming. First, we will print numbers from 1 to n and then n to 1 using recursion.
Program for printing 1 to n :
class recursion {
static void fun2(int n){
if(n>0){
fun2(n-1);
System.out.println(n);
}
}
public static void main(String[] args){
int n = 3;
fun2(n);
}
}
Output
1
2
3
2
3
In the above code, the print statement is getting executed at returning time.
Program for printing n to 1 :
class recursion {
static void fun1(int n){
if(n>0){
System.out.println(n);
fun1(n-1);
}
}
public static void main(String[] args){
int n = 3;
fun1(n);
}
}
Output
3
2
1
2
1
In the above recursive code, the print statement is getting executed at the calling time. Before the recursive function is called, printing was done.
Notice that by just changing the order of the print statement, the output of the code is completely reversed. This is the beauty of recursion. The same trick can be used to reverse a linked list.