Having trouble with recursive methods in c#. When compiled it should just display the total sumUpToo of all number for the given int, i.e
– input 10
– output 55 (10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0)
Im not able to find any info anywhere so if someone has a link to a website that can teach me how to go through it, would be greatly appreciated.
class Program
{
static void Main(string[] args)
{
public static int sum(int x)
{
Console.WriteLine("num");
x = Console.ReadLine();
int sum = 0, i = 0;
for (i = 0; i <= x; i++)
{
sum = sum + i;
}
Console.WriteLine("{0}", sum);
}
public static int recursivesum(int x)
{
if (x <= 1)
Console.WriteLine("{0}", x);
else
(x + Recursivesum(x - 1));
}
edit * This is the adjustment seems to be working fine now, if im not mistaken. Thanks for all the help
class Program
{
static void Main(string[] args)
{
int x;
Console.Write("Please enter an integer value to sum up to: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The sum of all numbers up to and including {0} is {1}",x, recursivesum(x));
}
public static int sum(int x)
{
int sum = 0, i = 0;
for (i = 0; i <= x; i++)
{
sum = sum + i;
}
return sum;
}
public static int recursivesum(int x)
{
if (x <= 1)
return x;
else
return x + recursivesum(x-1);
}
}
}
A recursive function is a function that calls it self. You need a base case that will exit the function and a recursive case where the function calls itself with modified parameters. Your function should look something like this:
So to use this function, you simple call it like this:
If you follow the logic of the function you will see this will return 10 + recursivesum(9). recursivesum(9) will return 9 + recursivesum(8). So now we have 10 + 9 + recursivesum(8).
This will carry on until we reach the point where we have 10+9+8+7+6+5+4+3+2+recursivesum(1). Now if you look at the function again, recursivesum(1) doesn’t call itself again. Instead it just returns x. So now the function will unwind and you’ll get the result you expect.
One final note on recursion. Recursion can be a wonderful elegant way to implement some algorithms, but it has it’s dangers. This site isn’t called stack overflow for nothing!