My Bookmarks

  • No bookmark found

Most Active Members

Write a program to find factorial of a given number in Java1 min read

AIM: – Write a program to find factorial of a given number.

Here, we have Write a program to find factorial of a given number in java with example to make the coding easier. Join our trending community to make us more stronger

Source Code: –

/*Scanner is a predefined class in java.util package used for reading the
* input  from the console of the primitive types like int, double, etc. and strings.
*/
import java.util.Scanner;

public class Factorial {

    public static void main(String args[]) {

        int num;
        long fact = 1;

        //Declaring an object of Scanner class
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number:- ");

        /*Obtaining integer from user using nextInt(method provided by Scanner class)
        * which returns the next token as an int value.
        */
        num = scanner.nextInt();

        //Calculating Factorial
        for(int i=num; i>1; i--) {
            fact = fact*i;
        }

        System.out.println("The factorial of " + num + " is " + fact);
    }
}

Output:

Bookmark(0)
Tags:

Add a Comment

Your email address will not be published. Required fields are marked *