+ 1

why out put is 55

Hi, I'm really confused why the output of this code is 55, if you can explain thanks class MyClass { public static void main (String [] args) { int result = sum (10); System.out.println (result); } public static int sum (int k) { if (k> 0) { return k + sum (k - 1); } else { return 0; } } }

1st Dec 2020, 10:26 AM
Amir Mardani
3 odpowiedzi
+ 3
Recursion
1st Dec 2020, 10:42 AM
Sanjar Egamberdiyev
Sanjar Egamberdiyev - avatar
+ 2
Recursion sum(10) = 10 + sum(9) = 10 + 9 + sum(8) .... until sum(0) return 0
1st Dec 2020, 10:29 AM
Gordon
Gordon - avatar
+ 1
Thank you so much
1st Dec 2020, 10:33 AM
Amir Mardani