Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Finding Factorial of a Number in Java

  • One of the famous java interview program for freshers is finding factorial of a number using java program
  • Calculating the factorial of a number using java example program with recursion.

  • Factorial number means multiplication of all positive integer from one to that number.
  • n!=1*2*3.......*(n-1)*n.
  • Here ! represents factorial.
  • Two factorial:   2!=  2*1=2
  • Three factorial: 3!= 3*2*1=6.
  • Four factorial :  4!= 4*3*2*1=24.
  • Five factorial:    5!= 5*4*3*2*1=120.
  • Six factorial:      6!= 6*5*4*3*2*1=720
  • Seven factorial: 7!= 7*6*5*4*3*2*1=5040
  • Eight factorial:   8!= 8* 7*6*5*4*3*2*1=40320.
  • By using loops we can find factorial of given number.
  • Lets how can we find factorial of a number using java program without recursion.

Program #1: Java program to find Factorial of a number using for loop


  1. package interviewprograms.instanceofjava;

  2. import java.util.Scanner;

  3. public class FactiorialProgram {

  4. public static void main(String args[]){
  5. Scanner in = new Scanner(System.in);
  6. System.out.println("Enter a number to find factorial");
  7. int n= in.nextInt();
  8. int fact=1;

  9. for (int i = 1; i
  10. fact=fact*i;
  11. }

  12. System.out.println("Factorial of "+n+" is "+fact);

  13. }
  14. }

Output:

  1. Enter a number to find factorial
  2. 5
  3. Factorial of 5 is 24


Program #2: Java program to find factorial of a number using recursion.

  1. package interviewprograms.instanceofjava;

  2. import java.util.Scanner;

  3. public class FactiorialProgram {

  4. public static void main(String args[]){
  5. Scanner in = new Scanner(System.in);
  6. System.out.println("Enter a number to find factorial");
  7. int n= in.nextInt();
  8. int fact=1;

  9. for (int i = 1; i
  10. fact=fact*i;
  11. }

  12. System.out.println("Factorial of "+n+" is "+fact);

  13. }
  14. }

Output:


  1. Enter a number to find factorial
  2. 5
  3. Factorial of 5 is 24

Program #3: Java program to find factorial of a number using recursion (Eclipse)





This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Finding Factorial of a Number in Java

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×