C/C++ Arena

Step 2 of 6

Loop over an array

Loops and arrays are best friends. The idiom:

int n = 5;
for (int i = 0; i < n; i++) {
    printf("%d\n", a[i]);
}

Note i < n, not i <= n. Using <= reads one past the end, a classic off-by-one bug.

The trick sizeof(a) / sizeof(a[0]) gives the number of elements of a real array (not of a pointer, as you'll see soon).

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

Previous: Declare and index Next: Read into an array