Arrays
Walk through a fixed array and accumulate its values without stepping past its bounds.
Complete program
#include <stdio.h>
int main(void) {
int values[] = {4, 8, -2, 10};
size_t count = sizeof values / sizeof values[0];
int sum = 0;
for (size_t i = 0; i < count; ++i) sum += values[i];
printf("Sum: %d\n", sum);
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Dividing the full array size by one element size gives the element count at the declaration site. Valid indexes run from zero through count - 1, so the comparison must be < rather than <=.
The sum starts at zero, the identity for addition. This sizeof technique does not recover a length from a pointer parameter; a function that receives the array must also receive its count.
Expected output
Sum: 20Concepts to practice
- Array indexing
- size_t
- sizeof
- Accumulator
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.