Java program to compute the factorial of given number
Program Description
Write a java program to compute the factorial of a given number.
IPO Chart
Input
We will take input from the user for the given number. Let’s call this number n.
Process
Compute n!
n! = (n)*(n-1)*(n-2)*…… * 1
Output
The program will output n! for the given n number.
Java Program
import java.util.Scanner; /************************************************** * FactorialNumber.java * @program : Factorial of n * @web : www.TestingDocs.com * @version : 1.0 **************************************************/ public class FactorialNumber { public static void main(String args[]){ int i,fact; Scanner keyboard= new Scanner(System.in); System.out.println("Enter n : ="); int number= keyboard.nextInt();//It is the number to calculate factorial // positive number part if(number>= 0) { fact=1; for(i=1;i<=number;i++){ fact=fact*i; } } //negative number part else { fact=1; for(i=1;i<=-number;i++){ fact=fact*i; } fact = fact*-1; } System.out.println("Factorial of "+number+" is: "+fact); } }
Program Output
Enter n : =
5
Factorial of 5 is: 120
Screenshot
Factorial program using Recursion:
https://www.testingdocs.com/questions/factorial-java-program-using-recursion/