简体   繁体   中英

Summing up integers in an array and storing the result in an array

I am attempting to do this for a smaller example so that I can do it for a larger sample.

Here is my attempted code:

int counts[0];
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < 10; i++)
    counts[0] += numbers[i];

printf("%d ", counts[0]);

This should yield 55, but my output is only 14. There is an issue with how I am setting up the numbers array, but I am not quite sure how to fix this. Any help is appreciated, thank you.

int counts[0];   // This declares an array that holds ZERO elements!  No place to store a value.
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < 10; i++)
    counts[0] += numbers[i];

printf("%d ", counts[0]);

To fix it:

int counts = 0;   // Declare a variable, and start it at 0
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < 10; i++)
    counts += numbers[i];

printf("%d ", counts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM