Write a java program to find the Factorial of a number
Answer :
/*
List Even Numbers Java Example
This List Even Numbers Java Example shows how to find and list even
numbers between 1 and any given number.
*/
public class FactorialExa1
{
public static void main(String[] args)
{
int number = 5;
/*
Factorial of any number is! n.
For example, factorial of 4 is 4*3*2*1.
*/
int factorial = number;
for(int i =(number - 1); i > 1; i--)
{
factorial = factorial * i;
}
System.out.println("Factorial of the number is " + factorial);
}
}
output: Factorial of the number is 120
Using Recursion
class FactorialExa2
{
static int factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[])
{
int i,fact=1;
int number=5;
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
output: Factorial of 5 is 120
No comments:
Post a Comment