How to loop through array elements in C++

Overview

To loop through an array is to repeat elements in the array multiple times until a particular condition is satisfied. In this shot, we’ll learn a couple of ways to loop through an array in C++.

Looping through an array

We use the following two ways to loop through an array:

  1. for loop
  2. while loop

for loop example

#include <iostream>
#include <string>
using namespace std;
int main() {
// creating an array
string names[3] = {"Theo", "Ben", "Dalu"};
for(int i = 0; i < 3; i++) {
cout << names[i] << "\n";
}
return 0;
}

Explanation

  • Line 7: We create a string type of array names. It has 3 string elements.

  • Line 8: We declare an integer i. It counts the iterations of the for loop with an increment of 1.

  • Line 9: We print the element at each index i of the array names in each iteration.

while loop example

#include <iostream>
using namespace std;
int main() {
string names[3] = {"Theo", "Ben", "Dalu"};
int i=0;
while (i < 3) {
cout << names[i] << " ";
i++;
}
}

Explanation

  • Line 5: We create a string type of array names. It has 3 string elements.

  • Line 6: We declare an integer i. It counts of the number of iterations.

  • Line 7: We use the while loop to declare a condition i < 3. The program will execute the conditions inside the body of the while loop until the value of i exceeds 3.

  • Line 8: We print the element present at index i of the array names.

  • Line 9: We increment the index variable i by 1.

Free Resources