Print factorials for any given number

In this example we are going to write a java class which will enable us to print factorial for any given number.
A quick refresher: 
  • The factorial of 0 and 1 is always 1.
  • Formula to find a factorial is: n! = n*(n-1)!
  • Exp: 5 = 5*4*3*2*1 = 120

import java.util.Scanner;

public class PrintFactorials {

    public int factorials() {
        int factorial = 1;
        int input;
        System.out.print("Please enter any integer value. ");
        Scanner scanner = new Scanner(System.in);
        input = scanner.nextInt();

        if (input < 0)
            System.out
            .println("The entered number is not positive!!! Please re-try...");
        else {
            for (int counter = 1; counter <= input; counter++)
                factorial = counter * factorial;
            System.out
            .println("The factorial of " + input + " is " + factorial);
        }
        return factorial;
    }

    public static void main(String[] args) {

        PrintFactorials pf = new PrintFactorials();
        pf.factorials();
    }
}


Output:

Please enter any integer value. 5
The factorial of 5 is 120


No comments:

Post a Comment