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:
forloopwhileloop
for loop example
#include <iostream>#include <string>using namespace std;int main() {// creating an arraystring 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 has3string elements. -
Line 8: We declare an integer
i. It counts the iterations of theforloop with an increment of1. -
Line 9: We print the element at each index
iof the arraynamesin 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 has3string elements. -
Line 6: We declare an integer
i. It counts of the number of iterations. -
Line 7: We use the
whileloop to declare a conditioni < 3. The program will execute the conditions inside the body of thewhileloop until the value ofiexceeds3. -
Line 8: We print the element present at index
iof the arraynames. -
Line 9: We increment the index variable
iby1.