Doing Factorial in Java
/*
* Factorial returns the factorial n!
* 2012.12.19
* Tetsuro
*/
public class Factorial {
// constructor for Factorial class
public Factorial() {
}
// this method returns n!
public int fact(int n) {
if (n == 0) {
return 1;
}
else {
return n * fact(n - 1); // fact(n - 1) always returns 1
}
}
}
|
public class RecursionTest {
/**
* Program for testing factorial object
*/
public static void main(String[]
args) {
// instantiating f from Factorial
class
// created object f
Factorial f = new Factorial();
// run the factorial f with
passing integer 5
// and print the result
System.out.print(f.fact(5));
}
}
|
Example:
Factorial, “3!” works like this:
No comments:
Post a Comment