Java – Recursion

When a function calls itself, it is called Recursion. In another sense, with Recursion, a defined function can call itself. Recursion is a programming approach that makes code efficient and reduces LOC.

Factorial with Recursion

The following figure demonstrates how recursion works when we calculate Factorial in Java with Recursion:

Java Recursion

Recursion Example in Java

Let us now see how to find the factorial of a number in Java with Recursion:

class Studyopedia {
  // Our method
  static int factMethod(int n) {
    if (n >= 1) {
      return n*factMethod(n-1); // Recursive Calls
    } else {
      return 1; // Factorial 0 is 1
    }
  }

  public static void main(String[] args) {
    // Calling the method
    int res = factMethod(5);
    System.out.println("Factorial = "+res);
  }
}

Output

Factorial = 120

Sum of first n numbers with Recursion

Let us see an example to get the sum of the first n numbers with Recursion in Java:

// Recursion in Java
// Sum of first n numbers

class Demo111 {

    static int sumMethod(int n) {
        if(n>0) {
            return n + sumMethod(n-1); // recursive call
        }
        else {
            return 0;
        }
    }

    public static void main(String[] args) {
      System.out.println("Sum of first n numbers = "+sumMethod(5));
    }
}

Output

Sum of first n numbers = 15

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java Methods
Java Method Overloading
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment