Factorial of a number in Java

Factorial of a number in Java

Factorial of a number is the product of the number and all the numbers below it. For e.g. factorial of 5 (5!) is 5*4*3*2*1 = 120. The number must be a positive integer. Let’s see a program to find factorial of a number in Java.

1. Using while loop

import java.util.Scanner;
class factorial
{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
	System.out.println("Enter a number: ");
	int n=sc.nextInt();
	int f=1;
	while(n>1)
	{
	    f=f*n;
	    n--;
	}
	System.out.println("Factorial = "+f);
  }
}

2. Using for loop

import java.util.Scanner;
class factorial
{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
	System.out.println("Enter a number: ");
	int n=sc.nextInt();
	int f=1;
	for(;n>1;n--)
	    f=f*n;
	System.out.println("Factorial = "+f);
  }
}

Output-

factorial java output

Explanation-

The program will accept a number of integer data type. We initialize the variable ‘f’ as 1 and then multiply it with the number, then decrement the number. while/for loop will continue to execute until the specified condition is satisfied. After coming out of loop it will finally print the factorial of entered number.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. Scanner– Scanner is a class in java. util package used for obtaining the input.
  7. String[] args– Used for command line argument.
  8. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.
  9. System.in is an InputStream.

Conclusion-

So this was the program for finding Factorial of a number in java. We hope it was clear to you. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *