Wednesday, 23 December 2015

Java Program for find a given number is Factorial or Not ?



In this tutorial we are going to implement the factorial of a given number in 2 different ways.
  1. Taking input from the user and find the factorial of the number.
  2. Taking input from the user and find the factorial of given number using recursion. 

1. Finding the Factorial of a Given Number : 

package com.javaprogrampoint.factorial;

import java.util.Scanner;


public class FactorialDemo {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number whose factorial is to be found: ");
        int n = scanner.nextInt();
        int result = findFactorial(n);
        System.out.println("The factorial of " + n + " is : " + result);
    }

    public static int findFactorial(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result = result * i;
        }
        return result;
    }
}
 
Output:

Enter the number whose factorial is to be found: 6
The factorial of 6 is 720

2. Factorial of Given Number Using Recursion :

package com.javaprogrampoint.factorialrecursion;


public class FactorialRecursion {


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number whose factorial is to be found: ");

        int n = scanner.nextInt();

        int result = findFactorial(n);

        System.out.println("The factorial of " + n + " is : " + result);

    }


    public static int findFactorial(int n) {

        if (n == 0) {

            return 1;

        } else {

            return n * findFactorial(n - 1);

        }

    }

}

Output:

Enter the number whose factorial is to be found: 5
The factorial of 5 is : 120


No comments:

Post a Comment