Home / Data structures and Algorithms by Java Examples / Recursion / Simple Recursion Example in JAVA
Simple Recursion Example in JAVA
3615 views.
HelloRecursion.java
class HelloRecursion {
    
    //printUptoOne method prints n to 1 values.
    public static void printUptoOne(int n) {
        //base case n == 0 exit
        if (n == 0) {
            return;
        }
        else {
            //recursive case: n != 0 then print n and call n-1 to print.
            System.out.println(n);
            printUptoOne(n-1);
        }
    }
    
    public static void main(String[] args) {
        
        /*
         * Simple recursion
         * To print 5,4,3,2,1 series by using recursion
         *
         * Recursion: Recursion calling itself again and again.
         * Has two cases: Base case and Recursive case
         *
         * Base case: To ensure recursion terminates.
         * Recursive case: To call itself again for sub process.
         *
         */
        
        //Calling recursive method with n = 5;
        printUptoOne(5);
        
    }
}
Output
5
4
3
2
1
Related Examples
   Simple Recursion Example in JAVA
   Print array using recursion JAVA Example
   Recursion on ArrayList Strings in JAVA Example
   Factorial Program using Recursion in JAVA Example
   Fibonacci Series using Recursion in JAVA Example
   Tree Traversal with Recursion in JAVA Example
   Tree Traversal without Recursion Using Stack Class in JAVA Example
   Is ArrayList Ordered using Recursion in JAVA Example
   Tower of Hanoi using Recursion in Java Example
Copyright © 2016 Learn by Examples, All rights reserved