- 2

Explanation needed

can someone explanation me why the result is 5? [...] system.out.print(f(3)); [...] public static int f(int x){ if(x==0) return 2; else return 1+f(x-1); [...]

13th Jun 2017, 8:19 AM
Sirdisq
Sirdisq - avatar
2 Respuestas
+ 4
- first call of f() is done with parameter x==3 > enter in f() with x==3: - as x!=0, f(3) must return 1+f(x-1), - so call f() with x==2 > enter in f() with x==2: - as x!=0, f(2) must return 1+f(x-1), - so call f() with x==1 > enter in f() with x==1: - as x!=0, f(1) must return 1+f(x-1), - so call f() with x==0 > enter in f() with x==0: - as x!=0, f(2) return 2 - return 1+f(0) == 1+2 == 3 - return 1+f(1) == 1+(1+f(0)) == 1+3 == 4 - return 1+f(2) == 1+(1+f(1)) == 1+(1+(1+f(0))) == 1+4 == 5 - print the returned value by f(3) == 1+f(2) == 5
13th Jun 2017, 8:36 AM
visph
visph - avatar
- 1
Thx!
13th Jun 2017, 8:58 AM
Sirdisq
Sirdisq - avatar