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)); } } }

12th Sep 2020, 5:17 PM
Yahel
Yahel - avatar
7 Respuestas
+ 3
if (number == 0) { return 1; }
12th Sep 2020, 5:21 PM
M Tamim
M Tamim - avatar
+ 1
yahel for your code output => 4*3*2*1*0 =0 For the return 1 =>4*3*2*1=24
12th Sep 2020, 6:25 PM
Jayakrishna 🇮🇳
+ 1
M Tamim thanks 🙏🏼
12th Sep 2020, 8:35 PM
Yahel
Yahel - avatar
0
M Tamim , Thanks! but why does it matter?
12th Sep 2020, 5:28 PM
Yahel
Yahel - avatar
0
yahel bcz, return 0, multiplies the whole thing with 0, so the eventual result you get, is 0...!!
12th Sep 2020, 7:47 PM
M Tamim
M Tamim - avatar
0
M Tamim how does it multiply it by 0 if they are in different return statements? How can such a thing happen?
12th Sep 2020, 7:56 PM
Yahel
Yahel - avatar
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)
12th Sep 2020, 8:07 PM
M Tamim
M Tamim - avatar