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
?