Lesson 62 +10 XP

Looping Through an Array

Looping Through an Array

Arrays really shine when you loop: one loop can touch every element.

Print all elements

int myNumbers[] = {25, 50, 75, 100};

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

Output: the four values, one per line.

The loop pattern

  • int i = 0 starts at the first index.
  • i < 4 stops after the last index (size-1).
  • myNumbers[i] grabs the current element.

Setting every element

int myNumbers[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++) {
    myNumbers[i] = myNumbers[i] + 1;  // add 1 to each
}

Size gotcha

For loops you often write the size by hand. There are tricks with sizeof to compute it, but for now, keep the size in mind.

TL;DR

  • Loop with a counter from 0 to size-1.
  • Use the counter as the index: arr[i].
  • Loop to read or write every element.
  • A loop + array handles batches of data.