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(); } } }
4 odpowiedzi
+ 1
I wrote the code on visual studio and I get 22. I also Start Debugging but finally the solution is 22.
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
0
kewl
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);