Write code to Calculate factorial with recursive function - Java Object Oriented Design

Java examples for Object Oriented Design:Method Recursive

Description

Write code to Calculate factorial with recursive function

In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:

You can use the following code structure and fill in your logics.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println(factorial(input.nextInt()));
        input.close();

    }

    static int factorial(int n) {
        // your code here
    }
    
}

Solution

Demo Code


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println(factorial(input.nextInt()));
        input.close();//  w w  w.j av  a  2s.  c  om

    }

    static int factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
    
}

Related Tutorials