-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorialWithSteps.java
More file actions
25 lines (21 loc) · 867 Bytes
/
FactorialWithSteps.java
File metadata and controls
25 lines (21 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class FactorialWithSteps {
public static void main(String[] args) {
int n = -5; // Example negative input
int i = 1;
long product = 1;
if (n < 0) {
System.out.println("Cannot calculate factorial of negative number (" + n + ")");
System.out.println("Factorial is only defined for non-negative integers.");
return; // Exit the program
}
System.out.println("Calculating " + n + "! step by step:");
System.out.println("Start: product = 1");
do {
System.out.print("Step " + i + ": Multiply " + product + " × " + i);
product *= i;
System.out.println(" → product = " + product);
i++;
} while (i <= n);
System.out.println("\nFinal product: " + product);
}
}