A girl and a robot thinking together

Think together · Start with a story

A girl wants to give every classmate a card without missing anyone. She starts at position 0 and moves forward one space at a time.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Index 0Handle the first one
  2. Index 1Move to the next
  3. Keep goingStop at the end

Traversing means visiting a group of elements according to a plan, often one by one.

01What does it mean to traverse?

Traversing an array means visiting each element so you can read it, process it, or update it.

02Traverse an array using indexes

int a[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {
    std::cout << a[i] << ' ';
}
i=0 → a[0]→i=1 → a[1]→...→i=4 → a[4]

03Why write i < 5?

Because the valid indexes are 0, 1, 2, 3, and 4.

When i == 5, the loop has gone past the last element and must stop.

04Can you avoid indexes?

You can use a range-based for loop:

for (int value : a) {
    std::cout << value << ' ';
}

Each element's value is copied into value in turn.

05What if you need to change an element?

A range-based for loop can use a reference:

for (int& value : a) {
    value = value + 1;
}

Here, value refers to each array element, so changing it changes the original array.

06How can you avoid hard-coding the length?

For an actual array object, use C++17's std::size:

for (std::size_t i = 0; i < std::size(a); i++) {
    std::cout << a[i];
}

If the array's length changes, this makes it less likely that you will forget to update the loop too.

What you have learned

  • Traversing means visiting array elements one by one.
  • Index-based traversal usually goes from 0 to n-1.
  • A loop condition is often written as i < n.
  • A range-based for loop can avoid manually managing indexes.
  • A reference lets a range-based for loop modify elements directly.

Next: How Do You Find the Maximum and Minimum?

Your turn to try

For an array of length 3, is accessing indexes 1, 2, and 3 a correct, complete traversal?

Ready? Open to see the explanation

No. It misses 0 and accesses 3, which is out of bounds. The correct forward order is 0, 1, 2.