Recursion 

A recursive method is a method that calls itself over and over again and again. It's a different methods of doing a loop. Lets see a simple recursion that finds a factorial.

/*
    The program uses recursive to find the factorial

*
*/


import java.util.*;

public class Factorial
{
    public static void main(String[] args)
    {

        Scanner key = new Scanner(System.in);

        int number;

      
 // Gets the number from the user

        System.out.println("Enter a nonnegative integer: ");
        number = key.nextInt();

        /*
            Pass number into factorial method
            outputs the factorial

        *
        */


        System.out.println(number + "!" + " is " + factorial(number));

    }

   // Recursive method

    private static int factorial(int n)
    {
       
// Base class

        if(n==0)
        {
            return 1;
        }

        else
        return n*factorial(n-1);
    }
}

ClickHere to download Factorial.java

In the example above the factorial is called with whatever argument passed into n. Although, return n * factorial(n-1) is a return statement but it does not return something immediately. The return statement will be call recursively until we reach to the base case which is n == 0. When the parameter reaches to 0, the method returns a value without making another recursive call.

/*
    The program demonstrates how to sum using recursive method

*
*/


import java.util.*;

public class RecursiveSum
{
    public static void main(String[] args)
    {
        Scanner key = new Scanner(System.in);
        int size;

       
// Gets the array size

        System.out.print("How many numbers do you want to sum: ");
        size = key.nextInt();

       
// Creates an array

        int[] array = new int[size];

       
// Gets the number

        for(int i=0; i< array.length; i++)
        {
            System.out.print("Enter the number: ");
            array[i] = key.nextInt();
        }

      
 // Pass the array, start index and the size into method sum

        System.out.println("The sum is " + sum(array, 0, size));

    }

  
// This is the recursive method

    public static int sum(int[] num, int start,int end)
    {
       
// Base case

        if(start == end)
            return 0;

        else
            return num[start] + sum(num, start+1, end);
    }

}

ClickHere to download RecursiveSum.java

The above example, we have a base case for start == end, so the recursive method will end when we have the start index equals to the end index. Note: the start index for array is always 0, and the end index is whatever the size of the array.

If we enter 3, the size of the array is 3. In the recursive method, start increases by 1, then once it reaches to 3 which is our base case, the recursive method ends.

 

 

  <Java 24><Home>