Factorial using java

In this article, we are going to print factorial of any number using java code.

Example :-if n=5,

solution:- 5*4*3*2*1=120

What is factorial?

The factorial of any number is equal to the product of all positive numbers less then or equals to that number.

Steps:-

  • Take a non negative input n from user using scanner.
  • create a variable result initialize it by 1 because factorial of 0 is 1.
  • Run a loop while(n>0)
  • result =result*n.
  • decrement n by 1.
  • end of loop.
  • Print result.

Java code to print factorial:-

package gangforcode;

import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		System.out.println("Enter the number");
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		int result=1;
		while(n>0) {
			result=result*n;
			n--;
		}
		System.out.println(result);
		}

}

Output:-

Java code to print factorial

You can use the same logic to find the factorial of any number in any other languages like c,c++, python etc.

Leave a Comment