Q:

Java program for Factorial

0

Java program for Factorial

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Core Java Example programs for Beginners and Professionals

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to print Fibonacci Series... >>
<< Java program for Prime Number | Check whether Numb...