+ 2
Why does sum hasn't been initialized to 0 during every time when it calling itself,by the way, what does static means in here?
using System; using System.Collections.Generic; namespace SoloLearn { class Program { static int Counter(ref int x) { int sum = 0; sum += x; if (x == 1) { return sum; } else { x = x - 1; return sum+Counter(ref x); } } static void Main(string[] args) { int a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Counter( ref a)); } } }
4 odpowiedzi
+ 2
Yasswecancn
Program is working fine. What you expect here?
sum is initialise with 0 but you assigned again x to sum. So sum will have some value.
0
Yes,but shouldn't sum be ing initialized when I calling it at start of next
Loop/iteration?
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Sum( ref number));
}
static int Sum( ref int num)
{
int sum = 0;
sum += num;
if (num == 0)
{
Console.WriteLine(sum);
return sum;
}
num--;
return sum + Sum( ref num);
//complete the recursive method
}
}
}
0
Here is a similar code I've been dealing with. It has the same algorithm, but I still didn't get it because how could sum in the WriteLine box is 0,and 1 line later it turns into 15 if you enter 5?