I am practicing recursion and I can't see why this method does not seem to work. Any ideas?
public void fact()
{
fact(5);
}
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
}
Thanks
Your code seems to work but you are not doing anything with the returned value, put method call fact
or fact(5)
inside of a System.out.println
and see what you get.
The recursion part is fine; you're just not using its return
value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:
public class Factorial {
public static String fact(int n) {
if(n == 1){
return "1";
}
return n + " * " + (fact(n-1)); // what happens if you switch the order?
}
public static void main(String[] args) {
System.out.println(fact(5));
// prints "5 * 4 * 3 * 2 * 1"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With