Using recursion to sum numbers

后端 未结 16 2069
轮回少年
轮回少年 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:00

    Actually, I think you don't need to check case else because

    public static int sum(int number){
        if(number > 0){
           return number + sum(--number);
        }
        return number; // return 0 so that's why you don't need check else condition
    }
    
    0 讨论(0)
  • 2021-02-05 16:04

    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.

    0 讨论(0)
  • 2021-02-05 16:06

    Your terminating expression is at issue. When value == 0 (or lower), it should return a 0 rather than 1. For sake of efficiency (which, let's admit it here, obviously isn't a concern, otherwise recursion wouldn't have been used for this task), you should terminate the recursion at value == 1 and return a literal 1 to save one unnecessary level of recursion.

    0 讨论(0)
  • 2021-02-05 16:06

    It could also be written like this:

    public static int sum(int n){
        int total;
    
        if(n==1){
            total =1;
    
        }else{
            total = sum(n-1)+n;
        }
        return total;
    }
    
    0 讨论(0)
  • 2021-02-05 16:09

    That's because, when the value is = 0, you return 1. Then it get's added.

    Sum's "else" clause should return 0.

    0 讨论(0)
  • 2021-02-05 16:12

    You're returning 1 in the else clause. You should be returning 0:

    else
    {
        return 0;
    }
    

    If the value is not greater than zero, why would you return one in the first place?

    0 讨论(0)
提交回复
热议问题