Answer :
I'll show a few implementations, starting with the easiest to understand.
1.) While loop.
public static void main(String[] args) {
System.out.print(factorial(n));
}
public static int factorial(String n) {
int result = 1;
while(n > 0) {
result *= n;
n--;
}
return result;
}
2.) For loop (I'll just show the contents of the factorial(String) method):
int result = 1;
for (int i = n; i > 0; i--) {
result *= i;
}
return result;
3.) Recursively.
public static int factorial(int n) {
if(n == 1) return n;
return n * factorial(n-1);
}
1.) While loop.
public static void main(String[] args) {
System.out.print(factorial(n));
}
public static int factorial(String n) {
int result = 1;
while(n > 0) {
result *= n;
n--;
}
return result;
}
2.) For loop (I'll just show the contents of the factorial(String) method):
int result = 1;
for (int i = n; i > 0; i--) {
result *= i;
}
return result;
3.) Recursively.
public static int factorial(int n) {
if(n == 1) return n;
return n * factorial(n-1);
}