Find the factorial of a number using java.

Problem:- Write a program to find the factorial number using a while loop in Java?
Solution:- Let's see 1st what is the factorial number. The multiplication of all integers from 1 to the given number is called a factorial number. 
For example, factorial of 4 is = 4 * 3 * 2 * 1 =  24
Java code:- 

package com.codeforsolution.java.logical;

import java.util.Scanner;
public class FactorialNumber {

	public static void main(String[] args) {
		int num;
		Scanner s = new Scanner(System.in);
		try {

			System.out.println("Enter a number to find factorial");
			num = s.nextInt();
			if (num < 0) {
            
				System.out.println("Factorial not possible for the entered number " + num);
			} else {
				System.out.println("Factorial of given number is " + findFactorail(num));
			}
		} catch (Exception e) {
			System.out.println("Please enter a valid integer number");
		}

		s.close();
	}

	private static int findFactorail(int num) {
		int factorial = 1, i = 1;

		if (num == 0 || num == 1) {
			return factorial;
		} else {
			while (i <= num) {
				factorial = factorial * i;
				i++;
			}
		}
		return factorial;
	}
}


 

Output:- 
Enter a number to find factorial
4
The factorial of given number is 24
Post a Comment (0)
Previous Post Next Post