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

{\displaystyle n!=n\times (n-1)\times (n-2)\times (n-3)\times \cdots \times 3\times 2\times 1\,.}

Let take an example of factorial of 5

{\displaystyle 5!=5\times 4\times 3\times 2\times 1=120\,.}

Problem

Write a java code for factorial.

Code

import java.util.Scanner;

public class Factorial {
	public static int cnt;
	
	public static int facto(int num) {
		if(num == 0) {
			return 1;
		}
		
		return num * facto(num-1);
	}
	
	public static void main(String[] args) {
		System.out.println("Enter number  ");
        Scanner scanner = new Scanner(System.in);
        int cnt = scanner.nextInt();        
        scanner.close();
        
        System.out.print(Factorial.facto(cnt));
	}
}

Run Code

Similar Posts