ADVERTISEMENT
ADVERTISEMENT

Java program for Factorial

Factorial of an Integer Number - This program will read an integer number and find the factorial of given integer number.

Find Factorial of a Number using Java program

/*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);
  }
}

Output:

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

Using function/Method

//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);
  }
}

Core Java Example Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.