In C++ programming language, arrays are fundamental data structures that allow the storage of multiple elements of the same type in contiguous memory locations. They reserve contiguous memory locations for each element, making them efficient for accessing and manipulating the data. But the main question here is how you access each element individually. That’s where iteration comes in. Iterating through an array involves accessing each element sequentially, performing operations, and potentially modifying their values.
What Is Iteration?
Iteration, also known as looping, allows you to systematically visit each element in an array, performing operations and potentially modifying their values. Iterating through an array in C++ refers to repeating a function or a statement until the condition is met. Think of it like going through a bookshelf: you need to visit each book individually to find the specific one that you want. Similarly, to access and handle every element in an array, you must iterate across it. This article explores various methods to iterate through C++ arrays, providing examples and insights into each approach.
Method 1: Using a Traditional “For” Loop
Among the various techniques for iterating through arrays in C++, the “for” loop stands out for its simplicity and clear control. It offers a structured approach to visiting each element in the sequence and provides a convenient access to their values.
A “for” loop is used in this example to iterate through the numbers array. The loop runs from 0 to the array size minus one, accessing each element using the “st” index. This code demonstrates a simple example of iterating through an array in C++ using a “for” loop. Every time an element in the array is iterated through, the loop issues the value of that element to the console. This fundamental concept in C++ programming forms the basis for many more complex operations involving arrays.
using namespace std;
int main(){
int nmbr[] = {5, 18, 2, 10, 80, 70};
for (int st = 0; st<sizeof(nmbr)/sizeof(nmbr[0]); st++){
cout<<nmbr[st]<<" ";
}
return 0;
}
Now, let us learn what each line of code is doing. The input and output operations are supported by the <iostream> header. The program starts with the “int main()” function which is the program’s entry point. An array named “nmbr” of type “int” is then initialized with five elements: 5, 18, 2, 10, 80, and 70. Next, the “for” loop is defined. Here’s a breakdown of the loop components:
int st = 0;: This initializes the “st” integer variable to 0. This variable acts as the loop counter.
st<sizeof(nmbr) / sizeof(nmbr[0]);: This is the loop condition. The loop continues as long as the value of “st” is less than the size of the array divided by the size of each element.
st++: This increments the value of “st” after each iteration.
The cout<<nmbr[st] << “ ” statement prints the element at the current “st” index to the console, followed by a space. Lastly, return 0 returns an exit code of 0 which indicates the successful program execution. The following is the output of the program:
Method 2: Using the Range-Based “For” Loop (C++11 Onward)
Using the range-based “for” loop, C++11 introduced a more concise and readable way to iterate through containers. C++11 introduced a game-changer for iterating through collections like arrays and vectors. This concise and readable syntax replaced the longer, less intuitive traditional “for” loop, making the code cleaner and easier to understand.
Think of it like this:
Traditional “For” loop: A complex, multi-line construction that requires explicit loop counter management and element indexing.
Range-Based “For” loop: A single, concise line that focuses on the element itself, eliminating any non-essential details.
This range-based “for” loop approach offers several benefits:
-
- Conciseness: Single-line iteration eliminates the need for counters and index calculations, making the code shorter and more readable.
- Readability: It focuses on the element being accessed rather than the iteration mechanics, leading to a more precise and a more intuitive code.
- Improved Maintainability: It eliminates the error-prone elements like loop counters, making the code easier to maintain and modify.
- Modern Syntax: It aligns with modern C++ coding styles, fostering a cleaner and more consistent code structure.
Now, let us explore an example of a range-based “for” loop to completely understand how it works:
using namespace std;
int main(){
string nameArray[] = {"Kalsoom_1", "Kalsoom_2", "Kalsoom_3", "Kalsoom_4", "Kalsoom_5"};
for (const string& NA : nameArray){
cout<<NA<<", ";
}
return 0;
}
The following is the output of the range-based “for” loop program:
Notice how the range-based loop achieves the same functionality in a single line, highlighting the element itself and eliminating unnecessary details. The range-based method utilizes the range that is provided by the array and automatically binds each element to the variable number within the loop. This eliminates the need for explicit loop counters and index calculations, making the code more readable and less prone to errors.
Every element in the array is visited and processed using both methods which delivers the identical result. However, the range-based “for” loop offers a more concise and modern approach, making it the preferred choice for most scenarios in C++11 and later versions.
The range-based “for” loop simplifies the syntax by directly iterating through the elements of the array without needing an explicit index. It enhances the code readability and reduces the risk of off-by-one errors.
Method 3: Using the Standard Library Algorithms
The C++ standard library algorithms offer a powerful and flexible alternative for iterating through arrays: std::for_each. Unlike the previous methods which are focused on element access, this approach emphasizes applying a specific function or operation to each array element. Let us demonstrate an example to help you understand how the “for_each” function works in the C++ iteration through array.
#include <iostream>
using namespace std;
int main() {
int numArray[] = {5, 4, 7, 11, 20};
auto square = [](int elem) { return elem * elem; };
for_each(begin(numArray), end(numArray), square);
for (int ns : numArray) {
cout << ns << " ";
}
cout << endl;
return 0;
}
Let’s explain the program step by step. The <algorithm> header grants access to the “std::for_each” function and other useful algorithms that are later used in the program. A “square = [](int elem) {return elem * elem;};” function is created that encapsulates the desired operation to be applied to each element. The “for_each” function passes the array’s starting and ending iterators and your operation as arguments. The “for_each” algorithm takes a range that is defined by iterators and applies the provided function to each element.
Here is the resultant output of the given program:
Conclusion
Iterating through arrays is a fundamental skill in C++, and multiple methods are available to achieve this task. Whether using the traditional loops, modern range-based loops, or the standard library algorithms, choosing the right method depends on the specific requirements and preferences of the programmer. Understanding these different approaches equips the developers with the flexibility to write an efficient and readable code when working with arrays in C++.