×

Java Programs

Java Practice

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

    
    me@linux:~$ javac Factorial.java 
    me@linux:~$ 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 »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.