Factorial of a given number using recursion.
public lass FactorialRecursion{
public static void main(String[] ar){
System.out.print("Enter a number : ");
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
double ans=fact(n);
System.out.println("The factorial of "+n+" = "+ans);
sc.close();
}
public static double fact(int num){
if(num==1){
return(1);
}else{
return(num*(fact(num-1))); //Calling itself again with a different value.
}
}
}
O/P: Enter a number : 5
The factorial of 5 = 120.0
with out recursion:
public class Factorial {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
int no=Integer.parseInt(br.readLine());
int fact=1;
for(int i=1;i<=no;i++){
fact=fact*i;
}
System.out.println("Factorial is: "+ fact);
}
public lass FactorialRecursion{
public static void main(String[] ar){
System.out.print("Enter a number : ");
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
double ans=fact(n);
System.out.println("The factorial of "+n+" = "+ans);
sc.close();
}
public static double fact(int num){
if(num==1){
return(1);
}else{
return(num*(fact(num-1))); //Calling itself again with a different value.
}
}
}
O/P: Enter a number : 5
The factorial of 5 = 120.0
with out recursion:
public class Factorial {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
int no=Integer.parseInt(br.readLine());
int fact=1;
for(int i=1;i<=no;i++){
fact=fact*i;
}
System.out.println("Factorial is: "+ fact);
}
}
0 comments:
Post a Comment