Using recursion to sum numbers

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

提交回复
热议问题