Calculate Factorial of a Number Using While Loop in Java



The factorial of a number is a fundamental concept in mathematics, representing the product of all positive integers up to that number. Calculating the factorial of a given number is a common problem in programming, and Java provides a straightforward way to achieve this using a 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.

Problem Statement

Given a number write a Java program to calculate the factorial using while loop.

Input

Enter the number to which you need to find the factorial:
5

Output

Factorial of the given number is: 120

Steps to Calculate the Factorial of a Given Number

Below are the steps to calculate the factorial of a given number using while loop:

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

Java Program to Calculate the Factorial of a Number

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

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

Code Explanation

The code begins by importing the Scanner class from java.util package to read user input. The main method prompts the user to enter a number, which is stored in the number variable. The factorial variable is initialized with 1, and the i variable is set to 1. The while loop runs as long as i is less than or equal to number. Inside the loop, the factorial is multiplied by i, and i is incremented by 1. Finally, the program prints the calculated factorial value. The code uses a while loop to iteratively multiply the numbers from 1 to the given number, effectively calculating the factorial.

Updated on: 2024-07-18T14:22:45+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements