Search code examples
cloopsfor-loopsuminteger

Sum of first n natural numbers


Trying to learn C I'm toying around a bit with some for loops and sums. I want to compute the sum of the first n natural numbers without using the mathematical formula n(n+1)/2. I have this code for it:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 100;
    int sum = 0;

    for (int ix = 0; ix <= n; ix++) {
        sum = sum + ix;
    }

    printf("Sum of the first %d natural numbers is %d\n", n, sum);
}

So for n = 100 I get the sum to be 5050, which is correct. I also get correct when I use n = 10000, however if I go for example n = 1000000 then I get the sum = 1784293664 but correct answer should be sum = 500000500000.

Why does my program stop working when n becomes larger and what is that number of the sum being displayed when n = 1000000?


Solution

  • If you want to calculate a sum of natural numbers then instead of the type int use the type unsigned int.

    Correspondingly declare the variable sum as having the type unsigned long long int to decrease the risk of overflow.

    For example

    unsigned int n = 100;
    unsigned long long int sum = 0;
    
    for ( unsigned int ix = 1; ix <= n; ix++){
       sum = sum + ix;
    }
    
    printf("Sum of the first %u natural numbers is %llu\n" , n, sum);
    

    Or you could include the header <inttypes.h> and use the type uintmax_t for the variable sum as it is shown in the demonstrative program below.

    #include <stdio.h>
    #include <inttypes.h>
    
    int main(void) 
    {
        unsigned int n = 1000000;
        uintmax_t sum = 0;
    
        for ( unsigned int ix = 1; ix <= n; ix++){
           sum = sum + ix;
        }
    
        printf("Sum of the first %u natural numbers is %" PRIuMAX "\n" , n, sum);
        
        return 0;
    }
    

    The program output is

    Sum of the first 1000000 natural numbers is 500000500000
    

    Pay attention to that there is no need to introduce the auxiliary variable ix. The loop can look simpler as for example

    #include <stdio.h>
    #include <inttypes.h>
    
    int main(void) 
    {
        unsigned int n = 1000000;
        uintmax_t sum = 0;
    
        while ( n ) sum += n--;
        
        printf( "Sum of the first %u natural numbers is %" PRIuMAX "\n" , n, sum );
        
        return 0;
    }