java_logo

Java Factorial Code

The factorial function (symbol: !) means to multiply a series of descending natural numbers. Examples:

4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040

import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		
		System.out.print("Enter any number: ");
		
		int i =  in.nextInt();
		
		System.out.print(i + "! is " + factorial(i));
		
	}
	
	private static int factorial(int n) {
		
		if(n <= 0) {
			return (1);
		} else {
			return (n * factorial(n-1));
		}
		
	}
	
}

Output:

Enter any number: 4
4! is 24

One thought on “Java Factorial Code

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.