Arrays are data of the same type stored in contiguous locations in memory. To access or address an array, we use the starting address of the array. Arrays h**e indexing, using which we can access the elements of the array. In this article, we take a look...
Arrays are data of the same type stored in contiguous locations in memory. To access or address an array, we use the starting address of the array. Arrays h**e indexing, using which we can access the elements of the array. In this article, we take a look at methods to iterate over an array. This means accessing the elements that are present in an array.
The most common method of iterating over an array is using for loops. We use a for loop to iterate through an array in the next example. One thing is to be noted, we need the size of the array in this.
for ( init; condition; increment ) { statement(s); }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
Similar to for loop, we can use while loops to iterate through an array. Also in this case the size of the array has to be known or determined.
while(condition) { statement(s); }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
We can also use the modern for-each loop to iterate through the elements in the array. The major plus side of this method is we do not need to know the size of the array.
for (datatype val : array_name) { statements }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
Various ways of iterating through an array in C++ are described in this article. The main drawback of the first two methods is that the size of the array has to be known beforehand, but if we use the for-each loop, that problem can be mitigated. for-each loops support all STL containers and are easier to use.