Create a Java program to find the factorial using recursive and iterative method

 


public class CDM_varargs {
static int factorial(int n){
if(n==0 || n==1){
return 1;
}
else{
return n*factorial(n-1);

}
}
static int factorial_iterative(int n){
if(n==0 || n==1){
return 1;
}
else{
int product = 1;
for(int i =1; i<=n; i++){
product = product*i;

}
return product;

}
}

public static void main(String[] args) {
int x= 5;
System.out.println(" The value of factorial x is :" + factorial(x));
System.out.println(" The value of factorial x is :" + factorial_iterative(x) );
}
}
//output
The value of factorial x is :120 The value of factorial x is :120 Process finished with exit code 0

Post a Comment

0 Comments