Q. Write a program in JAVA to find factorial of a number using following techniques: a. Iteration b. Recursion
Iteration:
import java.util.Scanner;
class fact1
{
public static void main(String args[])
{
int f=1,n,i;
Scanner sc=new Scanner(System.in);
System.out.println("enter number= ");
n=sc.nextInt();
for(i=0;i<=n;i++)
{
f=f*i;
f=f*i;
}
System.out.println("factorial= "+f);
}
}
Output:
enter number= 5
factorial= 120
Recursion:
import java.util.Scanner;class fact2
{
public static void main(String args[])
{
int a;
Scanner sc=new Scanner(System.in);
System.out.println("enter number= ");
a=sc.nextInt();
rec ob=new rec();
System.out.println("factorial of "+a+"= "+ob.facto(a));
}
}
class rec
{
int facto(int n)
{
if(n==0 || n==1)
return 1;
else
return n*facto(n-1);
}
}
Output:
enter number= 5
factorial of 5= 120
/*if you have any problem, comment below*/
Comments
Post a Comment