Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the sum of integers in an array

Tags:

arrays

c

I don't know if I'm just being a total fool, most likely I am, it's been a long day, but this isn't working as I want it to, and, well, I don't see why.

It should be able to have 11 numbers entered, a new number on each line, add them to the array, then total them, yet it's just not working. It's not stopping to exit the loop, even though I am incrementing i.

Any ideas?

int main(void) {
 int array[10];
 int i;
 int sum = 0;
  for ( i = 0; i < 11; i++){
   scanf("%d", &array[i]);
  }
  for (i = 0; i < 11; i++) {
   sum += array[i];
  }
printf("%d", sum);

return 0;

}

like image 877
PnP Avatar asked Nov 28 '11 19:11

PnP


1 Answers

You have 10 elements in the array, numbered 0 - 9. You are overflowing the buffer, so all bets are off. This is undefined behaviour.

like image 97
harald Avatar answered Sep 22 '22 20:09

harald