MOCKSTACKS
EN  # 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

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

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.

## Conclusion

In this page (written and validated by ) you learned about Java Recursion . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Object Oriented Programming.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.