MOCKSTACKS
EN
Questions And Answers

More Tutorials









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.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.