C++ · Arrays
Array traversal
Use C++ loops to sum an array, count matching elements and find a maximum, with accumulator initialization and traversal boundaries.
Practice this topic in the app Read the lesson in the app
Traversal order and initial values
An array is a row of numbered "cells"; traversal means walking from the first cell to the last cell and looking at each one.
The most common way to write it is to use a for loop, letting the index increase from 0 to n-1 (n elements in total):
int a[5] = {3, 1, 4, 1, 5};
for (int i = 0; i < 5; i++) {
cout << a[i] << " ";
}Common tasks during traversal:
• Find the sum of all elements: use the variable sum to accumulate
• Find the maximum/minimum value: first assume the 0th is the largest/smallest, then compare one by one
• Count the number that satisfy the condition: when one meets the condition, add 1 to the counter
After C++11 you can also use a range for loop: for (int x : a) reads a copy of the element; if you want to modify the original array, you can write for (int &x : a).
Sum, maximum and conditional counting
Example 1: Traversal for summation and maximum value
#include <iostream>
using namespace std;
int main() {
int a[5] = {3, 1, 4, 1, 5};
int sum = 0, maxVal = a[0];
for (int i = 0; i < 5; i++) {
sum += a[i];
if (a[i] > maxVal) maxVal = a[i];
}
cout << "sum=" << sum << endl; // 14
cout << "max=" << maxVal << endl; // 5
return 0;
}Complete the two tasks of summation (14) and finding the maximum value (5) in one traversal. maxVal is initially a[0]=3, and is continuously updated during the traversal.
Example 2: Count the number of even numbers
#include <iostream>
using namespace std;
int main() {
int a[] = {1, 2, 3, 4, 5, 6};
int cnt = 0;
for (int i = 0; i < 6; i++) {
if (a[i] % 2 == 0) cnt++;
}
cout << cnt << endl; // output 3
return 0;
}Traverse 6 elements; 2, 4, and 6 satisfy the even condition, and cnt is finally 3.
Tips
- The traversal range is indices 0 to n-1, n elements in total; the most common mistake is writing i<=n (out-of-bounds access to a[n]).
- When finding the maximum/minimum value, the initial value should be set to the first element of the array (a[0]), not 0 (all elements may be negative).
- Traversal is only access; do not arbitrarily insert or delete elements during traversal (it will affect subsequent indices).
- Range for (for(int x : a)) cannot change array elements inside the loop; if modification is needed, use a reference: for(int &x : a).
Prerequisites
Technical references
Scope note
This lesson is written by InfoCode and is not an official syllabus; the reference level is a site mapping and does not represent official levels, certification or eligibility. Practice records do not establish mastery or eligibility.
Reference level: GESP Level 3 (site mapping)