[sourcecode language="java"]
package myrnd;
public class Factorial {
public static void main(String[] args) {
int a = 5;
int result = 1;
while (a > 0) {
result *= a;
a--;
}
System.out.println("result is:" + result);
// using recursion.
System.out.println("factorial :" + factorial(5));
}
// another way using recursion.
public static int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
}
return n;
}
}
[/sourcecode]
No comments:
Post a Comment