fact) initialized to 1 to store the result.
for loop starting from 1 to the given number (n).
fact variable by the loop counter in each iteration.
fact after the loop completes.
public class FactorialProgram
{
public static void main(String[] args)
{
int no = 5;
if (no < 0)
{
System.out.println("Factorial is not defined for negative numbers.");
}
else
{
long fact = 1; // Variable to store the factorial result
// Calculate factorial using a loop
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
// Display the result
System.out.println("Factorial of " + no + " is: " + fact);
}
}
}
Factorial of 5 is: 120
import java.util.Scanner;
public class FactorialProgram
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number to find its factorial: ");
int no = scanner.nextInt();
if (no < 0)
{
System.out.println("Factorial is not defined for negative numbers.");
}
else
{
long fact = 1; // Variable to store the factorial result
// Calculate factorial using a loop
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
// Display the result
System.out.println("Factorial of " + no + " is: " + fact);
}
// Close the scanner
scanner.close();
}
}
Enter a number to find its factorial: 6 Factorial of 6 is: 720
Scanner class is imported to take user input.
no) is declared to store the user’s input.
scanner.nextInt() is used to read and store the input in the no variable.
for Loop to Calculate Factorial: no. In each iteration, the fact variable is multiplied by the loop counter (i).
fact.
fact is printed as the factorial of the given number.
scanner.close() method is used to close the input stream and release resources.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.