1
#include <stdio.h>

int main() {
    unsigned long int sum = 0LL;
    long i;
    for (i = 0LL; i < 100000000; i++) {
        sum = sum + i;
    }
    printf("%i", sum);
}

that's all of my code, and I am curious why it prints 887459712 instead of 4999999950000000, and how to fix this

Barmar
  • 741,623
  • 53
  • 500
  • 612
Rafal Strus
  • 35
  • 1
  • 6

1 Answers1

5

Your sum is declared unsigned long int, which is big enough for your expected result.
The problem is not overflow.

The problem is your printf statement is wrong.

You told it to print a "normal" sized int with %i, which only goes up to about 4.2 billion.

You should tell printf to print an unsigned long int, using %llu
It should be:

printf("%llu", sum);

IDEOne Link

Results

Success #stdin #stdout 0s 5376KB
4999999950000000
abelenky
  • 63,815
  • 23
  • 109
  • 159
  • See this question: https://stackoverflow.com/questions/2844/how-do-you-format-an-unsigned-long-long-int-using-printf – abelenky Apr 21 '22 at 21:00
  • 1
    4999999950000000 is a little more than 2^52, so `long int` (signed or not) is only a large enough container if you're working on a 64-bit system; on a 32-bit (or smaller) system, it's not enough. Since the OP didn't specify the platform, you might want to do that in your answer, or else suggest `long long int`, which is 64 bits either way. – Caleb Apr 21 '22 at 21:12
  • @Caleb Yes, and `long long` is implied by OP's use of `0LL` – Craig Estey Apr 22 '22 at 00:48