Monday, 4 July 2016

How To Find Factorial In Java

How To Find Factorial In Java
What is Factorial?
Factorial means the product of a given positive integer multiplied by all lesser positive integers.
In This post, we will find Factorial of an Integer in java with some simple codes so first, we will understand what is factorial?
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1


import java.util.Scanner;

class Factorial
{
   public static void main(String args[])
   {
      int a, c, fact = 1;

      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);

      a = in.nextInt();

      if ( a < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= a ; c++ )
            fact = fact*c;

         System.out.println("Factorial of "+a+" is = "+fact);
      }
   }
}

Factorial Program Using Loop In Java

class FactorialExample{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;//It is the number to calculate factorial
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  System.out.println("Factorial of "+number+" is: "+fact);
 }
}

Factorial Program Using Recursion
Here is the another Factorial Program in Java Using Recursion. But first we will understand what recursion is?
Q: What is recursion?
Recursion is a basic programming technique  use in Java, in recursion  a method calls itself to solve some problem. A process that uses this technique is recursive.


class FactorialExample2{
 static int factorial(int n){
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
 }
 public static void main(String args[]){
  int i,fact=1;
  int number=4;//It is the number to calculate factorial
  fact = factorial(number);
  System.out.println("Factorial of "+number+" is: "+fact);
 }