Q-02: Write a JAVA program to find the Factorial of a given number:
(i) Using Recursion
(ii) Using Iteration
    

Using Recursion


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; class RecursiveFactorial { static int findFactorial(int x) { if(x==0) { return 1; } else { return x * findFactorial(x-1); } } public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a Number: "); int x = input.nextInt(); System.out.println("The Factorial of "+ x +" is " + findFactorial(x)); } }

OUTPUT

cmd->  javac  RecursiveFactorial.java
cmd->  java  RecursiveFactorial

Enter a Number:  0
The Factorial of 0 is 1


  

Using Iteration


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; class IterativeFactorial { static int findFactorial(int x) { int fact = 1; for(int i=x; i > 0; i--) { fact *= i; } return fact; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a Number: "); int x = input.nextInt(); System.out.println("The Factorial of "+ x +" is " + findFactorial(x)); } }

OUTPUT

cmd->  javac  IterativeFactorial.java
cmd->  java  IterativeFactorial

Enter a Number:  5
The Factorial of 5 is 120