Java-Recursive Function

Recursive Function (Find Factorial Value)

The methods you have seen so far have been called from within other methods, but a method can also call itself. A method that calls itself is described as a recursive method, and the process is referred to as recursion. The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 x 2 x 3, or 6. Here is how a factorial can be computed by use of a recursive method :

Program

Program Source

class Factorial {
    
    int fact(int n)
    {
        if(n==1)
        {
            return 1;
        }else
            return n*fact(n-1);
    }
}
public class Javaapp {

    public static void main(String[] args) {
        
        Factorial f = new Factorial();
        System.out.println(f.fact(5));
    }
}

Leave a Comment