Write a recursive and nonrecursive function to compute n factorial And Java program to compute n factorial

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, The value of 0! is 1, 2! is 2, 3! is 6 etc.

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.
Function to compute n factorial using recursive method :

public int Factorial(int n)
{
	if (n == 0)
		return 1;
	else
		return n * Factorial(n-1);
}

 

now,lets write a java program to find factorial of given number using recursive method :

import java.util.Scanner;
class FactorialDemo{
   public static void main(String args[]){
    
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the number:");
      
      int num = scanner.nextInt();
      
      int factorial = fact(num);
      System.out.println("Factorial of entered number is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}

OUTPUT :
fact

so,our next question is how can we  find factorial of given number using nonrecursive method or we can say it Iterative method.

here is Function to compute n factorial using non-recursive method :

int factorial ( int input )
{
  int x, fact = 1;
  for ( x = input; x > 1; x--)
     fact *= x;

  return fact;

}

 

now,lets write a java program to find factorial of given number using nonrecursive method.

 

import java.util.Scanner;

public class Factorial {

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the number: ");
       int n = scanner.nextInt();
       int result = factorial(n);
       System.out.println("The factorial of " + n + " is " + result);
   }

   public static int factorial(int n) {
       int result = 1;
       for (int i = 1; i <= n; i++) {
           result = result * i;
       }
       return result;
   }
}

OUTPUT:
fact2

Leave a Reply