for loop with arrrayC++ 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: how to add elements in an array in for loop c++

int * myVar = new int [5];
for (int i = 0; i < 5; i++)
	myVar[i] = i

// 0 1 2 3 4 myVar in the array 

// delete stuff *optional*
delete [] myVar;
myVar = NULL; 

// free up memory declared on the stack

Tags:

Cpp Example