In This Program, The Factorial Method Takes An Integer N As An Argument And Returns The Factorial Of N. The Base Case For Recursion Is When N Is 0 Or 1, In Which Case The Factorial Is 1. Otherwise, It Recursively Calls The Factorial Method With N-1 And Multiplies The Result With N.
In The Main Method, We Define A Variable Number With The Desired Value For Which We Want To Calculate The Factorial. You Can Change This Value To Any Positive Integer You Want. The Program Then Calls The Factorial Method With The Given Number And Prints The Result.
public class Factorial {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int number = 5; // Change this to the desired number
int result = factorial(number);
System.out.println("Factorial of " + number + " = " + result);
}
}
When You Run This Program, It Will Output:
Factorial of 5 = 120

No comments:
Post a Comment