Factorial program in java


Write a program to find factorial of given number-

Formula : factorial of n = 1 * 2 * 3 *  ......* n ;
Example : 5 factorial = 1 * 2 * 3 * 4 * 5 = 120.


Factorial of number
class FactorialDemo { public static void main(String[] args) { int number = 5; int fact = 1; for (int i = 1; i <= number; i++) { fact = fact * i; } System.out.println("Factorial of " + number + "=" + fact); } }

Output: 
Factorial of 5=120


Factorial using Recursion : 

Factorial of number using recursion
class FactorialDemo { public static void mainFact2(String[] args) { int number = 5; System.out.println(fact(number)); } private static int fact(int n) { if (n <= 1) return 1; else return n * fact(n - 1); } }

Output: 120

No comments:

Post a Comment

JSP and Servlet

JSP and Servlet