for loop array print in 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: c++ print every element in array

#include<iostream>

int main()
{
 	int array[8] = {1,2,3,4,5,6,7,8};
  	int i = 0;
  
  	while (i <= sizeof(array)/sizeof(int))
    {
     	std::cout << array[i];
      	i++;
    }
}

Tags:

Cpp Example