java program to print factorial of a number

Here’s a Java program to print the factorial of a given number:

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int fact = 1;

        for (int i = 1; i <= num; i++) {
            fact *= i;
        }

        System.out.println("Factorial of " + num + " is " + fact);
    }
}

In this program, we first import the Scanner class from the java.util package to read input from the user.

We then prompt the user to enter a number using the System.out.print() function and read the input using the nextInt() function of the Scanner class.

Next, we declare an integer variable fact and initialize it to 1. We then use a for loop to iterate from 1 to the entered number and calculate the factorial by multiplying the current number with fact.

Finally, we display the calculated factorial using the System.out.println() function.

When you run this program and enter a number, the output will be:

Enter a number: 5
Factorial of 5 is 120

If you enter a non-negative number, the program will calculate the factorial for that number. If you enter a negative number, the output will be:

Enter a number: -5
Factorial of -5 is 1

This program is a basic example of how to print the factorial of a given number using Java.