Factorial in Java


Q. Write a Java program for Factorial Number

import java.util.Scanner;

public class FactorialNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Ask user to enter a number
        System.out.print("Enter a non-negative integer: ");
        int number = scanner.nextInt();

        long factorial = 1;

        // Check if number is negative
        if (number < 0) {
            System.out.println("Factorial is not defined for negative numbers.");
        } else {
            // Loop to calculate factorial
            for (int i = 1; i <= number; i++) {
                factorial *= i;
            }
            System.out.println("Factorial of " + number + " is: " + factorial);
        }

        scanner.close();
    }
}
 

Q. Write an algorithm for Factorial Number

 1. Start
2. Read an integer and store it in number
3. If number < 0, print "Factorial not defined" and stop
4. Initialize factorial = 1
5. Repeat from i = 1 to number:
    a. Multiply factorial = factorial * i
6. Print factorial
7. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.