Looping through an array with C

By

Learn how to loop through an array in C with a for loop, using a SIZE constant as the bound so you can read and print each element by its index.

~~~

To loop through an array in C you use a for loop, with a counter going from 0 to the array size. One of the main use cases of arrays is to be used along with loops, and this is the pattern you’ll write constantly.

Given an array like this:

const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };

You can iterate over each element using a for loop in this way:

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

The counter i starts at 0 because array indexes in C start at 0. The first element is prices[0], the last one is prices[SIZE - 1].

The condition i < SIZE keeps the loop inside the array. When i reaches 5, the loop stops.

You can do the same with a while loop, if you prefer:

int i = 0;
while (i < SIZE) {
  printf("%d\n", prices[i]);
  i++;
}

What if you don’t know the size?

C arrays don’t carry their own length. There’s no prices.length like in other languages. If the size is not stored in a constant, you can compute it with sizeof:

int prices[] = { 1, 2, 3, 4, 5 };
int size = sizeof(prices) / sizeof(prices[0]);

sizeof(prices) gives you the total bytes occupied by the array. Dividing by the size of one element gives the number of elements. With 4-byte integers, that’s 20 / 4 = 5.

Be careful: this trick only works in the scope where the array is defined. When you pass an array to a function, it decays to a pointer, and sizeof would return the size of the pointer instead. That’s why C functions that receive arrays almost always receive the length as a separate parameter too.

The classic off-by-one error

The most common mistake in this kind of loop is writing <= instead of <:

for (int i = 0; i <= SIZE; i++) {
  printf("%d\n", prices[i]); //reads past the end!
}

prices[5] does not exist. The valid indexes are 0 to 4. C won’t stop you, though: reading past the end of an array is undefined behavior. You might print a garbage number, or the program might crash, and often the compiler won’t warn you.

When a loop prints one weird extra value, check the condition first.

Tagged: C · All topics
~~~

Related posts about clang: