If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To calculate the factorial of a given number in Java, you can use a loop to multiply the number with its preceding integers until you reach 1. The factorial of a non-negative integer n is denoted by n! and is the product of all positive integers from 1 to n. Here's a Java program to calculate the factorial of a given number:
javaCopy code
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = 1; // Use long to handle large factorials
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
scanner.close();
}
}
Example output:
mathematicaCopy code
Enter a non-negative integer: 5
Factorial of 5 is: 120
In the program above, we take the user input for the number and store it in the variable number
. We use a for
loop to calculate the factorial of the number by multiplying factorial
with integers from 1 to number
. The result is stored in the factorial
variable. If the user enters a negative number, we print a message stating that the factorial is not defined for negative numbers.
Note: The factorial of large numbers can grow very quickly and may exceed the range of int
or long
data types. To handle large factorials, you can use BigInteger class from the java.math
package, which allows working with arbitrarily large integers. However, for most practical purposes, using long
should be sufficient.
Comments: 0