Factorial Program In Java

Factorial Program in Java:

Factorial of a number means the product of all positive descending integers. 
for example: If we want to calculate factorial of 5 then it will be written as 
5 x 4 x 3 x 2 x 1 = 120 . So 120 is the factorial of  5.
  

  Program to Print Factorial of a given number:



import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		
		int num, fact=1;
		
		Scanner sc = new Scanner(System.in);
		
		//Accepting input
		System.out.println("Enter a Number: ");
		num = sc.nextInt();
		
		for(int i=num; i>=1; i--) {
			fact = fact*i;
		}
		System.out.println("Factorial Of "+num+" is: "+fact);
	}

}



  Factorial Program using while loop:



import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		
		int num, fact=1;
		
		Scanner sc = new Scanner(System.in);
		
		//Accepting input
		System.out.println("Enter a Number: ");
		num = sc.nextInt();
		
		int i = num;
		
		while(i>=1) {
			fact = fact*i;
			i--;
		}
		System.out.println("Factorial Of "+num+" is: "+fact);
	}

}

  

Output:

Enter a Number: 7
Factorial of 7 is: 5040


No comments:

Post a Comment

If you have any doubts, please discuss here...👇