+ 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; } } }
3 Answers
+ 3
Recursion
+ 2
Recursion
sum(10)
= 10 + sum(9)
= 10 + 9 + sum(8)
....
until sum(0) return 0
+ 1
Thank you so much