Java Program for Factorial

You are currently viewing Java Program for Factorial

Java program for Factorial

/*Java program for Factorial - to find Factorial of a Number.*/

import java.util.*;

public class Factorial {
  public static void main(String args[]) {
    int num;
    long factorial;

    Scanner bf = new Scanner(System.in);

    //input an integer number
    System.out.print("Enter any integer number: ");
    num = bf.nextInt();

    //find factorial
    factorial = 1;
    for (int loop = num; loop >= 1; loop--)
      factorial *= loop;

    System.out.println("Factorial of " + num + " is: " + factorial);
  }
}
//Java program for Factorial - to find Factorial of a Number.

import java.util.*;

public class Factorial {
  //function to find factorial
  public static long findFactorial(int num) {
    long fact = 1;

    for (int loop = num; loop >= 1; loop--)
      fact *= loop;

    return fact;
  }

  public static void main(String args[]) {
    int num;
    long factorial;

    Scanner bf = new Scanner(System.in);

    /*input an integer number*/
    System.out.print("Enter any integer number: ");
    num = bf.nextInt();

    /*find factorial*/
    factorial = findFactorial(num);

    System.out.println("Factorial of " + num + " is: " + factorial);
  }
}

Output

    
    [email protected]:~$ javac Factorial.java 
    [email protected]:~$ java Factorial
    Enter any integer number: 7
    Factorial of 7 is: 5040

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply