how to loop through an array c++ code example

Example 1: lopping over an array c++

for (int i = 0; i < arr.size(); ++i){
//use if we explicitly need the value of i
cout << i << ":\t" << arr[i] << endl;
}
for (int element : arr){
//modifying element will not affect the array
cout << element << endl;
}
for (int &element : arr){
//modifying element will affect the array
cout << element << endl;
}

Example 2: for loop with array c++

int v[] = {1,2,3,4,5};
for (int n : v)
  cout << n << endl;
//make sure to compile with -std=c++11

Tags:

Cpp Example