A Cumulative Total – Solution

I find it odd that the recursive solution for this month’s Exercise is far shorter than the non-recursive version. Yet, it has an elegance that’s evident in lots of recursive code examples.

First, the non-recursive solution:

2020_10-Exercise-non-recursive.c

#include <stdio.h>

unsigned cumulative(unsigned n)
{
    unsigned a,total;

    total = 0;
    for(a=1; a<=n; a++)
    {
        total=total+a;
    }

    return(total);
}

int main()
{
    unsigned v;

    printf("Type a positive integer value: ");
    scanf("%u",&v);

    printf("The total of all numbers 1 through %u is %u\n",
            v,
            cumulative(v)
          );

    return(0);
}

The cumulative() function at Line 3 loops from 0 to n, the unsigned value passed. As it loops, the value of variable total is increased by the value of the looping variable, a. This variable is initialized to one in the for loop statement at Line 8. I could have started it at zero, but 0+0=0, which wastes a spin of the loop. Further, the maximum value is set to a<=n, to ensure the final value (which was passed in variable n) is added to the total.

Here’s a sample run:

Type a positive integer value: 10
The total of all numbers 1 through 10 is 55

The recursive version of the cumulative() function, shown below, is far more elegant — and short:

2020_10-Exercise-recursive.c

#include <stdio.h>

unsigned cumulative(unsigned n)
{
    while(n)
        return(n + cumulative(n-1));
    return(n);
}

int main()
{
    unsigned v;

    printf("Type a positive integer value: ");
    scanf("%u",&v);

    printf("The total of all numbers 1 through %u is %u\n",
            v,
            cumulative(v)
          );

    return(0);
}

I confess that I stewed over a solution. I knew it could be done, but I over-thought the problem. It was only when I decided to do some right-brain activities that the brilliance of return(n + cumulative(n-1)); came to me.

At Line 5, a while loop spins as long as the value of variable n is non-zero (positive). The return statement adds the value passed plus one minus the value, which is used to call the cumulative() function again. This process recurses until n is equal to zero, at which point the entire thing unwinds. A final return statement at Line 7 passes the cumulative total back to the caller.

Here’s sample output from the recursive version of the code:

Type a positive integer value: 200
The total of all numbers 1 through 200 is 20100

I hope you were successful in solving this month’s Exercise, especially if you attempted the recursive solution. Providing that the output is correct, consider the challenge completed successfully.

Leave a Reply