Arrays and Loops
Traditional For Loop
A common way to iterate over arrays is with a counter-based for loop.
Example
#include <iostream>
using namespace std;
int main() {
const int SIZE = 5;
int numbers[SIZE] = {10, 20, 30, 40, 50};
for (int i = 0; i < SIZE; i++) {
cout << "Element " << i << ": " << numbers[i] << endl;
numbers[i] *= 2; // Modify each element
}
return 0;
}
Output
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50
Range-Based For Loop (C++11)
Since C++11, a range-based for loop provides a cleaner and safer way to traverse arrays.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
// Read-only traversal (copies elements)
for (int num : numbers) {
cout << num << ' ';
}
cout << '\n';
// Modify elements in place (use a reference)
for (int &num : numbers) {
num *= 2;
}
// Show the modified result
for (int num : numbers) {
cout << num << ' ';
}
return 0;
}
Output
10 20 30 40 50 20 40 60 80 100
ℹ️ Note: Use a reference in the loop variable if you want to change the array elements. Use const reference (e.g., `for (const int& x : arr)`) to avoid copies without allowing modification.
While Loop with Arrays
While loops can also be used with arrays, especially when stopping conditions depend on the data.
⚠️ Warning: Always check array bounds to prevent accessing invalid memory.
Example
#include <iostream>
using namespace std;
int main() {
const int SIZE = 5;
int numbers[SIZE] = {10, 20, 0, 40, 50};
int i = 0;
while (i < SIZE && numbers[i] != 0) { // left-to-right: bounds check happens before element access
cout << numbers[i] << ' ';
i++;
}
}
Common Loop Patterns
Pattern | Example |
---|---|
Searching | for (int n : arr) if (n == target) { /* found */ } |
Summation | int sum = 0; for (int n : arr) sum += n; |
Finding Max | int mx = arr[0]; for (int n : arr) if (n > mx) mx = n; |
Transformation | for (int &n : arr) n *= 2; |