In C++, arrays are often used with loops to efficiently process multiple elements without manually handling individual values.
Looping Through an Array
Using a for loop, you can iterate through each element in an array.
Example: Displaying Motorcycle Brands
C++
x
using namespace std;
int main() {
// Create an array of motorcycle brands
string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};
// Loop through the array
for (int i = 0; i < 5; i++) {
cout << bikeBrands[i] << "\n";
}
return 0;
}
Output:
C++
Yamaha
Ducati
Kawasaki
Honda
Harley-Davidson
Displaying Index Alongside Values
To show the index along with each value, use i
within the loop.
Example
C++
using namespace std;
int main() {
string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << bikeBrands[i] << "\n";
}
return 0;
}
Output:
C++
0 = Yamaha
1 = Ducati
2 = Kawasaki
3 = Honda
4 = Harley-Davidson
Looping Through an Array of Numbers
Arrays can also store numerical values, such as engine capacities.
Example: Displaying Engine Sizes
C++
using namespace std;
int main() {
int engineSizes[5] = {600, 1000, 1100, 1300, 1500};
for (int i = 0; i < 5; i++) {
cout << engineSizes[i] << "\n";
}
return 0;
}
Output:
C++
600
1000
1100
1300
1500
The For-Each Loop (Range-Based Loop)
Introduced in C++11, the for-each loop (or range-based for loop) simplifies iteration by automatically handling each array element.
Syntax
C++
for (type variableName : arrayName) {
// Code to execute for each element
}
Example: Iterating Over Engine Sizes
C++
using namespace std;
int main() {
int engineSizes[5] = {600, 1000, 1100, 1300, 1500};
for (int cc : engineSizes) {
cout << "Engine displacement: " << cc << "cc\n";
}
return 0;
}
Example: Iterating Over Motorcycle Brands
C++
using namespace std;
int main() {
string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};
for (string brand : bikeBrands) {
cout << "Brand: " << brand << "\n";
}
return 0;
}