0

understanding C# Code

Can someone explain me that code in detail? I dont get it: class Program { static int Sum(int x) { if (x != 0) { return x + Sum(x - 1); } else return x; } static void Main(string[] args) { int x = 6; x = Sum(x); Console.WriteLine(++x); Console.ReadKey(); } } }

2nd Aug 2018, 7:09 PM
sahnebutter
sahnebutter - avatar
4 odpowiedzi
+ 1
I wrote the code on visual studio and I get 22. I also Start Debugging but finally the solution is 22.
2nd Aug 2018, 7:22 PM
sahnebutter
sahnebutter - avatar
0
return x + sum(x-1) return 6 + sum(6-1) return 5 + sum(5-1) ... return 1 + sum(1-1) and when x == 0 return x; in other word function sum runs while x != 0 and when x == 0 stops running. output ++x means 1
2nd Aug 2018, 7:18 PM
B K
0
kewl
2nd Aug 2018, 7:20 PM
Neyo XxR.I.P
Neyo XxR.I.P - avatar
0
Yes because see x = sum(x) so x = 6 + 5 + 4 + 3 + 2 + 1 = 21 ++x = 22 sorry i forget about this line x = Sum(x);
2nd Aug 2018, 7:27 PM
B K