C++ Looping Through Arrays
In this page:
Looping Through an Array with a for Loop
The standard way to loop through an array in C++ is a for loop whose index variable runs from 0 up to, but not including, the array's length, accessing one element per iteration with square-bracket indexing.
Example: Looping Through an Array with a for Loop
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4};
int length = 4;
for (int i = 0; i < length; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Looping with Range-Based for
A range-based for loop iterates directly over an array's elements without needing an explicit index variable, making the loop shorter and less error-prone.
Example: Looping with Range-Based for
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4};
for (int value : arr) {
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Summing Array Elements
A running total variable, initialized before the loop and updated inside it, is the standard pattern for summing every element in an array, which can then be divided by the count to compute an average.
Example: Summing Array Elements
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
int total = 0;
for (int i = 0; i < 3; i++) {
total += arr[i];
}
std::cout << total << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding a Value in an Array
Searching an array for a specific value loops through its elements checking each one against the target, and break is commonly used to stop the loop immediately once a match is found rather than continuing needlessly.
Example: Finding a Value in an Array
#include <iostream>
int main() {
int arr[] = {5, 8, 12, 3};
int target = 12;
for (int i = 0; i < 4; i++) {
if (arr[i] == target) {
std::cout << "Found at index " << i << std::endl;
break;
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Elements in a Loop
A loop can modify an array's elements in place by both reading and writing to the same index within its body, which is how operations like doubling every value or clamping negative values are applied across an entire array.
Example: Modifying Elements in a Loop
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
arr[i] *= 2;
}
for (int i = 0; i < 3; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings