C/C++ Arena

Step 2 of 7

Loop over an array

Arrays and loops go together: the loop counter becomes the index, so one loop can visit every element no matter how many there are.

#include <stdio.h>

int main(void) {
    double prices[] = {2.5, 4.0, 1.25, 3.75};
    int n = sizeof(prices) / sizeof(prices[0]);
    double total = 0;
    for (int i = 0; i < n; i++) {
        printf("item %d: %.2f\n", i, prices[i]);
        total += prices[i];
    }
    printf("%d items, total %.2f\n", n, total);
    return 0;
}
item 0: 2.50
item 1: 4.00
item 2: 1.25
item 3: 3.75
4 items, total 11.50

The standard loop

for (int i = 0; i < n; i++) visits indexes 0 through n-1: exactly the valid ones. The most common array bug is i <= n, which runs one extra time and reads a[n], one past the end. This mistake is so common it has a name: an off-by-one error.

Counting elements with sizeof

sizeof(prices) is the size of the whole array in bytes (4 doubles x 8 bytes = 32), and sizeof(prices[0]) is the size of one element (8). Dividing gives the element count (4). Computing it like this means the loop stays correct if you add items to the list later.

This only works where the array itself was declared. Once an array is passed to a function it becomes a pointer, and sizeof gives the pointer's size instead. You'll see this in a couple of steps.

Averages

Remember the integer division trap: if you sum ints and divide by an int count, cast one side to double first.

Your turn: print the average of the array with two decimals: avg 18.00.

Previous: Declare and index Next: Read into an array