Java Program to find Factorial of Number

 

Write a Java Program to find Factorial of Number – Java Tutorial

Java Program to find Factorial of Number

Problem Statement

 Write a Java program to find the factorial of a number ‘n’ using for loop.

Solution:

First, create a main class named Factorial. Then add the main method to the main class Factorial.

Declare local variables such as n – to store the value of a number, fact = 1 (Initial factorial values).

Create an object of the scanner class and read a number using the scanner class object and the nextInt() method.

Next loop over from n to 1 and multiply n to partial; factorial in every iteration.

Finally, display the result (factorial of number).

/*
 * Java Program to find the Factorial of a number
 * 
 * Subscribe to Mahesh Huddar YouTube Channel for more Videos
 */

import java.util.Scanner;

public class Factorial 
{
	public static void main(String args[])
	{
		int n, fact = 1;
		Scanner in = new Scanner(System.in);
		System.out.println("Enter the value of n:");
		n = in.nextInt();
		for (int i = n; i>=1; i--)
		{
			fact = fact * i;
		}
		System.out.println("The factorial of "+n+" is "+fact);
	}
}

The output of the Factorial Program in Java

Enter the value of n: 5

The factorial of 5 is 120

Summary:

In this article, we understood How to write a Java Program to find a Factorial – Java Tutorial. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and the YouTube channel for video tutorials.

Leave a Comment

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