C++ Arrays and Loops

Arrays and loops are a natural pair. Instead of writing a separate line for every element, you can use a loop to walk through the whole array in just a few lines. This becomes essential as arrays grow larger.

Looping Through an Array

A classic for loop uses a counter variable as the index. You start at 0 and keep going while the counter is less than the number of elements, increasing the counter by one each time.

Printing every element with a for loop

#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50};
  for (int i = 0; i < 5; i++) {
    cout << myNumbers[i] << "\n";
  }
  return 0;
}
// Output: 10 20 30 40 50 (each on its own line)

The Range-Based For Loop

Modern C++ offers a cleaner way to loop through an array without managing an index at all. The range-based for loop copies each element into a variable so you can use it directly. It is easier to read and avoids off-by-one mistakes.

A range-based for loop

#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50};
  for (int number : myNumbers) {
    cout << number << "\n";
  }
  return 0;
}
// Output: 10 20 30 40 50 (each on its own line)

Getting the Array Size

In modern C++ you can find how many elements an array has with sizeof(array) / sizeof(array[0]). This divides the total memory the array uses by the memory of a single element. Using it in the loop condition means you do not have to hard-code the size.

  • sizeof(myNumbers) gives the total bytes used by the whole array.
  • sizeof(myNumbers[0]) gives the bytes used by one element.
  • Dividing the two gives the element count, which is safer than typing a number by hand.
Note: Prefer the range-based for loop when you just need each value. Use the classic indexed for loop when you also need the position, such as when you want to modify elements or print their index.
Loop styleBest forAccess to index
Indexed forModifying elements, needing positionsYes
Range-based forReading each value simplyNo