Using recursion to sum numbers

后端 未结 16 2072
轮回少年
轮回少年 2021-02-05 15:45

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, an

相关标签:
16条回答
  • 2021-02-05 16:24

    Your code executes as follows:

    Sum --> 5
      Sum --> 4
        Sum --> 3
          Sum --> 2
            Sum --> 1
              Sum --> 0
              1 <---
            2 <---
          4 <---
        7 <---
      11 <---
    16 <---
    

    Check your base case.

    0 讨论(0)
  • 2021-02-05 16:25
    static int Sum(int value)
    {
        if (value > 0)
        {
            return value + Sum(value - 1);
        }
        else
        {
            return 0; //Change this.
        }
    }
    
    0 讨论(0)
  • 2021-02-05 16:25

    The others have already answered that question, but when I work with recursion, one of the things I like to do to check that it works is to use check the base case and one additional case. I your case I would test it with 1, which would yield 2. Since this is obviously wrong you might want to check for 0 which is not going to use any recursion and so it should be obvious that the error lies in the base class.

    In general recursion is easier to reason about, since you can list the limited number of things you need to check, but it does initially require a leap of faith since your intuition will be wrong. Just test the edge cases and trust the math it will never fail.

    0 讨论(0)
  • 2021-02-05 16:26
    int summation(int num){
    
        if (num==1)
            return 1;
    
        return summation(num-1)+num;
    }
    
    0 讨论(0)
提交回复
热议问题