Loop Through Array

Loop Through Array in C++: An array is a shelf of numbered slots. Looping over it is walking the shelf and doing something with each item.

The Analogy: Walking the Shelf

An array is a shelf of numbered slots. Looping over it is walking the shelf and doing something with each item. There are only three ways to walk it, and choosing the right one is most of what this lesson is about.

You can count the slots — "slot 0, slot 1, slot 2" — which you need when the position itself matters. You can just take each item in turn, ignoring where it sits, which is what you want most of the time. Or you can hold a finger on the current slot and slide it along, which is how the standard library does it internally.

The first is an index loop, the second is a range-based for, the third is an iterator. Same walk, different amounts of ceremony.


Syntax or Core Structure

#include <iostream>
#include <array>
#include <vector>

int main() {
    std::array<int, 5> data{10, 20, 30, 40, 50};

    // 1. Index loop -- you have the position
    for (std::size_t i = 0; i < data.size(); ++i) {
        std::cout << i << ":" << data[i] << " ";
    }
    std::cout << "\n";

    // 2. Range-based -- read only, no copies. The default choice.
    for (const int& value : data) {
        std::cout << value << " ";
    }
    std::cout << "\n";

    // 3. Range-based with a reference -- modify in place
    for (int& value : data) {
        value *= 2;                     // data is now {20, 40, 60, 80, 100}
    }

    // 4. Iterators -- explicit begin and end
    for (auto it = data.begin(); it != data.end(); ++it) {
        std::cout << *it << " ";        // * gets the value at the position
    }
    std::cout << "\n";

    // 5. Backwards
    for (auto it = data.rbegin(); it != data.rend(); ++it) {
        std::cout << *it << " ";        // 100 80 60 40 20
    }
    std::cout << "\n";

    return 0;
}

Note it != data.end() rather than <. end() points one past the last element — a valid position to compare against but never to dereference.


Technical Depth: Copies, Invalidation and the Algorithms

The ampersand is not optional decoration

std::vector<std::string> names{"Ada", "Alan", "Grace"};

for (std::string s : names)        { s += "!"; }   // copies each string, edits the copy
for (std::string& s : names)       { s += "!"; }   // edits the real elements
for (const std::string& s : names) { std::cout << s; }   // reads, zero copies
for (const auto& s : names)        { std::cout << s; }   // same, and shorter

For int the copy is free. For a string, an object, or a struct with several members, every pass allocates and destroys. In a loop over a million records that is a million pointless copies. const auto& for reading, auto& for writing — make it a reflex.

Never resize while you iterate

std::vector<int> v{1, 2, 3};

for (const int& x : v) {
    v.push_back(x);      // UNDEFINED BEHAVIOUR: push_back may reallocate,
}                        // leaving the loop's iterator pointing at freed memory

// Erasing has the same problem
for (auto it = v.begin(); it != v.end(); ++it) {
    if (*it == 2) { v.erase(it); }    // it is now invalid; ++it is undefined
}

// Correct: erase returns the next valid iterator
for (auto it = v.begin(); it != v.end(); ) {
    if (*it == 2) { it = v.erase(it); }   // no ++ here
    else          { ++it; }
}

// Better: the erase-remove idiom, one line
#include <algorithm>
v.erase(std::remove(v.begin(), v.end(), 2), v.end());

A std::vector that grows past its capacity moves its contents to a new block of memory, and every pointer, reference and iterator into the old block becomes dangling. This is the classic C++ container bug. If you must add or remove during a pass, collect the changes and apply them after — or use the algorithms.

Common loop shapes

std::array<int, 6> data{4, 8, 15, 16, 23, 42};

// Accumulate
int total{0};
for (const int& x : data) { total += x; }

// Find the extreme, and where it is
int largest{data[0]};
std::size_t at{0};
for (std::size_t i = 1; i < data.size(); ++i) {         // start at 1, not 0
    if (data[i] > largest) { largest = data[i]; at = i; }
}

// Count matches
int evens{0};
for (const int& x : data) { if (x % 2 == 0) { ++evens; } }

// Search and stop early
bool found{false};
for (const int& x : data) { if (x == 15) { found = true; break; } }

// Compare each element with its neighbour -- note size() - 1
bool ascending{true};
for (std::size_t i = 0; i + 1 < data.size(); ++i) {
    if (data[i] > data[i + 1]) { ascending = false; break; }
}

The neighbour loop is written i + 1 < size() rather than i < size() - 1 on purpose: if the container is empty, size() - 1 on an unsigned type wraps to an enormous number and the loop runs away.

The library already wrote these loops

#include <algorithm>
#include <numeric>

const int total   = std::accumulate(data.begin(), data.end(), 0);
const auto maxIt  = std::max_element(data.begin(), data.end());
const auto found  = std::find(data.begin(), data.end(), 15);
const int evens   = std::count_if(data.begin(), data.end(),
                                  [](int x) { return x % 2 == 0; });
const bool sorted = std::is_sorted(data.begin(), data.end());

if (found != data.end()) {
    std::cout << "at index " << (found - data.begin()) << "\n";
}

Each replaces a hand-written loop with a named intention. std::accumulate needs <numeric>; the rest need <algorithm>. They are correct by construction, and the name at the front tells the reader what the loop is for rather than making them decode it. Note the pattern for a search result: compare against end() to check success, and subtract begin() to recover the index.

Which loop to reach for

NeedUse
Read every elementfor (const auto& x : c)
Modify every elementfor (auto& x : c)
The index mattersfor (std::size_t i = 0; i < c.size(); ++i)
Two containers in stepindex loop
Compare neighboursfor (i = 0; i + 1 < c.size(); ++i)
Backwardsrbegin() / rend()
Sum, find, count, sortan algorithm from <algorithm>

Real World Example: Grade Statistics

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

int main() {
    const std::vector<std::string> students{
        "Ada", "Alan", "Grace", "Edsger", "Barbara"
    };
    std::vector<int> marks{88, 54, 97, 71, 63};

    // 1. Aggregate with an algorithm rather than a loop
    const int total = std::accumulate(marks.begin(), marks.end(), 0);
    const double mean = static_cast<double>(total) / marks.size();

    // 2. Index loop: two containers walked in step
    std::cout << std::fixed << std::setprecision(1);
    for (std::size_t i = 0; i < students.size(); ++i) {
        std::cout << std::setw(9) << std::left << students[i]
                  << std::setw(4) << std::right << marks[i];

        // A nested loop draws a bar, ten marks per block
        std::cout << "  ";
        for (int b = 0; b < marks[i] / 10; ++b) { std::cout << "#"; }
        std::cout << "\n";
    }

    // 3. Extremes, with the index recovered from the iterator
    const auto topIt = std::max_element(marks.begin(), marks.end());
    const auto lowIt = std::min_element(marks.begin(), marks.end());
    const std::size_t topAt = static_cast<std::size_t>(topIt - marks.begin());
    const std::size_t lowAt = static_cast<std::size_t>(lowIt - marks.begin());

    // 4. Count with a predicate
    const auto passes = std::count_if(marks.begin(), marks.end(),
                                      [](int m) { return m >= 60; });

    // 5. Modify every element in place: scale by 5%, capped at 100
    for (int& m : marks) {
        m = std::min(100, static_cast<int>(m * 1.05));
    }

    std::cout << "\nMean:    " << mean << "\n";
    std::cout << "Top:     " << students[topAt] << " (" << *topIt << ")\n";
    std::cout << "Lowest:  " << students[lowAt] << " (" << *lowIt << ")\n";
    std::cout << "Passing: " << passes << " of " << marks.size() << "\n";
    std::cout << "Ada after scaling: " << marks[0] << "\n";
    return 0;
}

Every loop form appears here doing the job it is best at. The aggregate and the search are algorithms, because accumulate and max_element say what they mean. The report needs an index because it walks two vectors together — no range-based loop can do that. The bar is a nested loop with a computed count. And the final adjustment uses int& because it must write back into marks; drop the ampersand and the scaling silently applies to throwaway copies. Note that the iterators are captured before the modifying loop: after marks is changed, *topIt would report the new value, not the original top mark.


Common Mistakes

  • Forgetting & in a modifying range-based loop. It compiles, runs, and changes nothing.
  • Copying by value in a read-only loop over strings or objects — invisible performance loss.
  • push_back or erase during iteration. Iterators, pointers and references are invalidated.
  • i < size() - 1 on a possibly-empty container. Unsigned wraparound gives a runaway loop; write i + 1 < size().
  • Dereferencing end(). It is one past the last element, for comparison only.
  • Not checking a search result against end() before dereferencing it.
  • Starting a max-finding loop at i = 0 when you already seeded from data[0] — harmless, but starting at 1 says what you mean.
  • Seeding largest = 0 instead of data[0]. All-negative data then reports zero.

Best Practices

  1. Range-based for by default. Drop to an index loop only when you need the position.
  2. const auto& to read, auto& to write. Never plain auto for a non-trivial element type.
  3. Prefer an algorithm over a hand-written loop when one exists — the name documents the intent.
  4. Never modify a container's size while looping over it.
  5. Use std::size_t for indices so it matches .size() and does not warn.
  6. Seed running extremes from the first element, and guard against an empty container first.
  7. Extract the body into a function once it grows past a dozen lines; a named function beats a long loop.

Practice Exercises

  1. Three ways: Sum a std::vector<int> with an index loop, a range-based loop, and std::accumulate. Confirm all three agree, then say which you would ship and why.
  2. Second largest: Find the second largest value in one pass, handling duplicates correctly so {5, 9, 9, 2} reports 5. Test with an array of length 1.
  3. Safe filtering: Remove every negative number from a std::vector<int>, first with the erase-and-reassign iterator loop, then with the erase-remove idiom. Explain why the naive for (auto it : v) v.erase(it) is undefined behaviour.