Understanding C++: Arrays and Loop Structures
C++ Arrays and Loops Looping Through an Array In C++, you can traverse the elements of an array using a loop. Below are some examples illustrating how to iterate over an array:...
C++ Arrays and Loops
Looping Through an Array
In C++, you can traverse the elements of an array using a for loop. Below are some examples illustrating how to iterate over an array:
For instance, consider an array named cars. You can use a for loop to display each element within it. Another example shows how to access both the index and its corresponding value for each element in the array. Additionally, you can apply this method to arrays containing integers.
The For-Each Loop
Introduced in C++11, the "for-each" loop is a convenient tool for iterating over the elements of arrays and other data structures like vectors and lists. Here are some examples demonstrating how to utilize a "for-each" loop to output all elements of an array.
Code Example:
#include <iostream>
using namespace std;
int main() {
string cars[3] = {"Toyota", "Honda", "Ford"};
for (int i = 0; i < 3; i++) {
cout << cars[i] << " ";
}
return 0;
}