C++ Arrays and Loops: Several Methods to Traverse an Array

In C++, an array is a collection of multiple elements of the same type, and a loop is a tool for repeatedly executing a code block. When we need to process each element in an array, we use the method of “traversing” the array. Today, we’ll explore several common ways to traverse arrays in C++, from simple to advanced, suitable for beginners to master step by step.

1. Array Basics Review

First, let’s recall what an array is. An array is a set of elements of the same type, stored contiguously in memory. For example, to define an array containing 5 integers:

int arr[5] = {1, 2, 3, 4, 5};  // Defines an array with 5 elements, values 1~5

Important note: Array indices start at 0. Thus, the first element is arr[0], the second is arr[1], and the last element is arr[4] (since indices for 5 elements range from 0 to 4).

2. Why Traverse an Array?

Traversing an array means accessing each element one by one. Common use cases include:
- Printing all elements (e.g., outputting array contents)
- Calculating the sum, average, or maximum value of elements
- Modifying array elements (e.g., incrementing each element by 1)

Loops are the most common tool for traversal. Let’s explore combinations of loops and arrays.

3. Array Traversal Methods

Method 1: Traditional for Loop (with Index)

This is the most basic traversal method, using a loop variable i as the array index to access elements sequentially.
Steps:
1. Define the array and loop variable i
2. Loop condition: i is less than the array length (note: the maximum index is n-1 when the array length is n)
3. Loop body: Access the i-th element via arr[i] and perform operations (e.g., print, calculate)
4. Update the loop variable i (increment by 1)

Code Example:

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);  // Calculate array length (5)

    // Traverse the array
    for (int i = 0; i < n; ++i) {
        cout << "Element " << i << ": " << arr[i] << endl;
    }
    return 0;
}

Output:

Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5

Use Case: When you need to know the element index (e.g., modifying elements at specific positions or calculating results based on indices).

Method 2: while Loop for Array Traversal

Similar to the for loop, the while loop can also traverse arrays using an index i, but with a different structure (condition checked first, then the loop body is executed).

Code Example:

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int i = 0;  // Initialize index variable

    while (i < n) {  // Condition: i is less than the array length
        cout << "Element: " << arr[i] << endl;
        i++;  // Update index (same as i++ in for loop)
    }
    return 0;
}

Output is the same as Method 1.
Note: The while loop requires manually managing the initialization and update of the loop variable i. Forgetting to write i++ can cause an infinite loop, so beginners are advised to master the for loop first.

Method 3: Range-based for Loop (C++11 and above)

Introduced in C++11, this is a concise traversal method that does not require manual indexing and directly iterates over elements.

Syntax:

for (element_type variable : array_name) {
    // Operate on each element (the variable holds the current element's value)
}

Code Example:

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};

    // Traverse the array; 'num' takes the value of each element in turn
    for (int num : arr) {
        cout << "Current element: " << num << endl;
    }
    return 0;
}

Output:

Current element: 1
Current element: 2
Current element: 3
Current element: 4
Current element: 5

Key Points:
- The variable num copies the value of each element in the array, not a reference to the original element. To modify the original array elements, use a reference type: for (int& num : arr) (note the & symbol).
- Use Case: When only the element values are needed (e.g., printing all elements or summing values).

Method 4: Pointer-based Array Traversal (Underlying Understanding)

The array name is essentially a pointer to the first element of the array. This method is more low-level and helps understand array storage, but it is recommended for beginners to first learn the above methods.

Code Example:

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int* p = arr;  // p points to the first element of the array (arr is equivalent to &arr[0])

    // Traverse using a pointer: *p represents the current element, p++ moves to the next element
    for (int i = 0; i < n; ++i) {
        cout << "Element: " << *p << endl;  // *p is equivalent to arr[i]
        p++;  // Move the pointer forward by one position (equivalent to i++)
    }
    return 0;
}

Output is the same as above.
Supplement: You can also use p[i] instead of *p (since arr[i] is equivalent to *(arr + i), and p[i] is equivalent to *(p + i)).

4. Method Comparison and Selection

Method Type Advantages Disadvantages Use Cases
Traditional for loop Flexible use of index (i) Requires manual range for i Modifying specific indices, calculating sum
Range-based for loop Concise code, no need for index Cannot directly modify original elements (requires reference) Simple traversal, only element values needed
while loop Intuitive structure (check first, execute later) Prone to infinite loops if i is forgotten to be updated Dynamic loop control based on conditions
Pointer traversal Understands array storage (low-level) Difficult for beginners Low-level programming, performance optimization

5. Summary

Traversing arrays is a fundamental skill in C++ programming. Beginners are advised to prioritize:
1. Traditional for loop (with index): A universal foundation suitable for most scenarios.
2. Range-based for loop: Recommended for C++11 and above, concise and efficient for simple traversals.

For more complex operations (e.g., dynamic index adjustment or element modification), you can further explore while loops or pointer traversal. Remember: array indices start at 0, and the loop condition should avoid out-of-bounds errors (e.g., i < n instead of i <= n). This is crucial for avoiding bugs!

By practicing different traversal methods, you will gradually become familiar with the combination of arrays and loops, laying a solid foundation for more complex programming tasks.

Xiaoye