Factorial of a number:
import java.util.Scanner;class Factorial
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int n=sc.nextInt();
int f=1;
for(int x=1;x<=n;x++)
{
f=f*x;
}
System.out.println("Factorial of " + n + " is " + f);
}
}
Input:
Enter any number
5
Output:
Factorial of 5 is 120
Factorial of a number using Recursion:
import java.util.Scanner;class Factorial
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int n=sc.nextInt();
int f=fact(n);
System.out.println("Factorial of " + n + " is " + f);
}
public static int fact(int x)
{
if(x<=1)
return 1;
return x*fact(x-1);
}
}
Input:
Enter any number
5
Output:
Factorial of 5 is 120

0 Comments
Please don't enter any spam link in comment box.
Emoji