Alex Rivera | Logout

Using recursion to sum numbers

Asked 2009-04-24T13:40:24.677
14

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, and add them together using recursion. I expected the result to be 15, but my code is returning 16.

What am I doing wrong?

Code:

    static void Main(string[] args)
    {
        
        Console.WriteLine(Sum(5));
        Console.Read();
    }


    static int Sum(int value)
    {
        if (value > 0)
        {
          return value + Sum(value - 1);
        }
        else
        {
            return 1;
        }
    }
Edit
Report

1 Answer

4

I always prefer to put the terminating case(s) up front so they're obvious, and I have a violent near-psychopathic hatred of "if cond then return a else return b" constructs. My choice would be (making it clear that it won't work properly for negative numbers):

static unsigned int Sum(unsigned int value) {
    if (value == 0)
        return 0;
    return value + Sum(value - 1);
}

I believe that's far more readable than a morass of braces and control flow.

answered 2009-04-24T13:50:44.807

Your Answer