Follow @devglan
Write a Java Program to find Factorial of a Given Number
Description
Write a program to find factorial of a given number is a common java program asked in any interview to freshers.The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2 = 24.There are 2 ways to find a factorial of a given number - One by using for loop and the other using recursion.Following java program uses for loop to find factorial of a given number.
Factorial.javapackage com.devglan; public class Factorial { public long findFactorial(int num){ if(num < 1){ System.out.println("Please provide non-negative number."); } long factorial = 1; for (long i = num; i > 1; i--) { factorial = factorial * i; } return factorial; } public static void main(String [] args){ Factorial factorial = new Factorial(); int num = 34; System.out.println("Factorial of " + num + " is : " + factorial.findFactorial(num)); } }
Explanation
Click to Suggest Your Own Explanation
Use for loop starting from the number itself and multiply with a decrement number and keeps on accumulating the result in the same variable untill 1 is reached.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.