Java program to calculate the factorial of a given number using while loop


A factorial of a particular number (n) is the product of all the numbers from 0 to n (including n) i.e. Factorial of the number 5 will be 1*2*3*4*5 = 120.

  •  To find the factorial of a given number.
  •  Create a variable factorial initialize it with 1.
  •  start while loop with condition i (initial value 1) less than the given number.
  •  In the loop, multiple factorials with i and assign it to factorial and increment i.
  •  Finally, print the value of factorial.

Example

import java.util.Scanner;
public class FactorialWithWhileLoop {
   public static void main(String args[]){
      int i =1, factorial=1, number;
      System.out.println("Enter the number to which you need to find the factorial:");
      Scanner sc = new Scanner(System.in);
      number = sc.nextInt();

      while(i <=number) {
         factorial = factorial * i;
         i++;
      }
      System.out.println("Factorial of the given number is:: "+factorial);
   }
}

Output

Enter the number to which you need to find the factorial:
5
Factorial of the given number is:: 120

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 13-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements