0
why isnt it working? (factorial program)
public class Main { public static void main(String[] args) { int fact = 4; int myNum = factorial(fact); System.out.println(myNum); } public static int factorial(int number){ if (number == 0){ return 0; }else{ return (number * factorial(number -1)); } } }
7 Respuestas
+ 3
if (number == 0)
{
return 1;
}
+ 1
yahel for your code output => 4*3*2*1*0 =0
For the return 1 =>4*3*2*1=24
+ 1
M Tamim thanks 🙏🏼
0
M Tamim , Thanks! but why does it matter?
0
yahel
bcz, return 0, multiplies the whole thing with 0, so the eventual result you get, is 0...!!
0
M Tamim how does it multiply it by 0 if they are in different return statements? How can such a thing happen?
0
yahel
look, suppose the number is 3,
so, you get,
return(3 * factorial(3-1))
now, factorial(3-1) returns 2*factorial(2-1)
so we get,
→ return(3*2*factorial(1))
→ return(6*1*factorial(0))
now, fact(0) returns 0,
so we get
→ return(6*0)
→ 0
that's how we get 0, though they are under two different return statements. (simple recursion)