Factorial Program in Java with examples.

Factorial Program in Java 


Factorial:  Factorials are products of every whole number from 1 to n Factorials are introduced in algebra. The value of 0! is 1, according to the convention for an empty product. The notation n! was introduced by the French mathematician Christian Kramp in 1808.

Formula:

n! = n(n-1)(n-2)(n-3)(2)(1)

 (or)

n! = n.(n-1)!.

Example:

4! =  4*(4-1)*(4-2)*(4-3)*(4-4)
4! =  4*3*2*1
4! = 24

Factorial program:

class Fact
{
 public static void main(String args[])
 {
  int fact = 1,j = 6;
  for(int i = 1;i<=j;i++)
  {
   fact = fact * i ;
  }
 System.out.println("Fact of 6 = "+fact);
 }
}

Output:

Fact of 6 = 720

Factorial program using user entered value:

import java.util.Scanner;
class Fact1
{               
 public static void main(String args[])
 {
  Scanner s = new Scanner(System.in); 
  int fact = 1;
  System.out.print("Enter the value of j = ");
  int j = s.nextInt();
  for(int i = 1;i<=j;i++)
  {
   fact = fact * i ;
  }
 System.out.println("Fact of " + j + " = " +fact);
 }
}

Output:

Enter the value of j = 10
Fact of 10 = 3628800

Factorial using recursion:

class FactorialRecursion
  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; 
  FactorialRecursion f1 = new FactorialRecursion();
  fact = f1.factorial(5);  
  System.out.println("Factorial of 5 = "+fact);   
 } 

Output:

Factorial of 5 = 120

Recursion program using user entered value:

import java.util.Scanner;
class FactorialRecursion1
  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; 
  Scanner s = new Scanner(System.in);
  FactorialRecursion1 f1 = new FactorialRecursion1();
  System.out.print("Enter the value of J = ");
  int j = s.nextInt();
  fact = f1.factorial(j);  
  System.out.println("Factorial of J = "+fact);   
 } 

output:

Enter the value of J = 6
Factorial of J = 720

Share:

Search This Blog

  • ()

Our Services

Powered by Blogger.

Top 20 Websites like Bookzz | Bookzz Alternatives Websites

The domain  Bookzz.org  isn’t into work anymore, and the world’s largest ebook library  Bookzz  has got a new domain name or its Alternati...