Beginner in C language. I suspect it may be due to overflow, but could not solve this simple exercise: program to compute the sum of squares of all the natural numbers smaller than 10000
I initially tried:
#include <stdio.h>
int main() {
int a = 10000;
int square(int num) {
return num * num;
};
int total = 0;
while (a > 0) {
a--;
total += square(a);
//printf("a is %d and square is %d and total %d \n", a, square(a), total );
};
printf("total is %d ", total );
return total;
}
result: total is -1724114088
and here there's the strange thing:
...
a is 9936 and square is 98724096 and total 2063522144
a is 9935 and square is 98704225 and total -2132740927
...
So I tried to change total to long
, tried to change declaring square function as long square(int num )
, but nothing changed.
Could you explain why the sum turns negative ? Is it due to overflow ? But why not resetting to 0 or positive, instead of going negative ? how can I know how many bits for int are there in a computer that I don't know (e.g. cloud ? E.g. I am coding here: [https://www.programiz.com/c-programming/online-compiler/]