Coding Practice

Write a Java program to calculate factorial of a number

Calculate factorial of a number
Sample Output
Calculate factorial of a number.

Enter a number: 5

Factorial of 5 = 120
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int n, number, fact = 1;

        Scanner input = new Scanner(System.in);

        System.out.println("Calculate factorial of a number.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        for (n = 1; n <= number; n++) {
            
            fact = fact * n;
        }
        System.out.print("\nFactorial of " + number + " = " + fact + "\n");
    }
}
Sample Output
Calculate factorial of a number.

Enter a number: 4

Factorial of 4 = 24

No comments:

Post a Comment

Change Theme
X