A Cumulative Total

I remember the first time I heard the puzzle: If you’re paid a penny on the first day, doubled on the second day, and doubled every day after, by the end of the month you’d be a millionaire many times over. This concept is mind boggling.

Here’s code I wrote that demonstrates the puzzle:

2020_10_01-Example.c

#include <stdio.h>

int main()
{
    int days,d;
    float total;

    printf("Number of days in the month: ");
    scanf("%d",&days);

    total = 0.01;
    for(d=1;d<days;d++)
    {
        total *= 2;
    }
    printf("At the end of %d days, you have $%.2f\n",
            days,
            total
          );

    return(0);
}

This month has 31 days, so here’s the sample run:

Number of days in the month: 31
At the end of 31 days, you have $10737418.00

Mathematicians and others with large brains explain that the value obtained is calculated as 2n-1 where n is the number of days in the month.

Another fun, cumulative math thing is the factorial. This value is calculated as the product of a whole number and all smaller integers down to 1. So 5! (read as “five factorial”) is 5×4×3×2×1 = 120. Calculating a factorial is also possible in C; refer to my 2014 series on this topic, which also covers recursion.

One other cumulative math thingie, without a clever name I’m aware of, is to add the numbers. Yes, it’s far more boring than the penny-a-day puzzle or factorials, but it’s something you can program in C: Take a value, such as 200. If you were to add all the integers from 1 to 200, what would be the result?

Don’t bother doing the math in your head! Code the puzzle in C: Your task is to write a program with the cumulative() function. Prompt the user for positive integer input. Call the cumulative() function to return the cumulative total of the value input, n + n-1 + n-2 + n-3 all the way down to one.

Further, to make the program more interesting, make the cumulative() function recursive to counterbalance the boring aspect of this Exercise.

Click here to view my solution, though please try this Exercise on your own before checking out what I’ve done.

3 thoughts on “A Cumulative Total

  1. This is a story about Carl Friedrich Gauss:
    https://www.americanscientist.org/article/gausss-day-of-reckoning

    There is an old legend about some king who wanted to reward one of his subjects for something or other and told him he could have anything he wanted. The subject asked for a grain of rice on the first square of a chessboard, two grains on the second square etc. The king didn’t realise that by the time you got to 64 that was a lot of rice.

  2. I don’t think it has a name other than something like “sum of consecutive non-negative integers” which isn’t very catchy. Maybe it doesn’t have many practical uses (unlike factorial) so doesn’t need a name.

Leave a Reply