Programming Tutorials

Recursion in java

By: aathishankaran in Java Tutorials on 2007-03-08  

Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive

public class RecursionExample {
    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println(n + "! = " + result);
    }
    
    public static int factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

This program calculates the factorial of a number n using recursion. The factorial() function calls itself with a smaller value of n until n equals 1, at which point it returns 1. The results of these recursive calls are multiplied together to give the final result.

For example, when n is 5, the program calculates 5! as follows:

5! = 5 * 4 * 3 * 2 * 1
   = 120

The factorial() function is called recursively with the values 4, 3, 2, and 1, and their results are multiplied together to give the final result of 120.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)