42.2k views
0 votes
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5!=5 *4* 3* 2* 1 =120 Write a programn (in Java) to print and calculate the factorial for a given (n) number

User Gabor
by
4.8k points

1 Answer

3 votes
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);
}
User Michael Ekoka
by
5.1k points