Home > Article > Backend Development > C++ program to iterate over array
Array is a continuous storage of the same type of data in memory. To access or address an array, we use the starting address of the array. Arrays have indexing, using which When addressing an array, we use the starting address of the array. Arrays have indexes and can be accessed through indexes We can access the elements of the array. In this article, we will introduce ways to iterate over arrays Operate on an array. This means accessing the elements present in the array.
for ( init; condition; increment ) { statement(s); }
#include <iostream> #include <set> using namespace std; // displays elements of an array using for loop void solve(int arr[], int n){ for(int i = 0; i < n; i++) { cout << arr[i] << ' '; } cout << endl; } int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << "Values in the array are: "; solve(arr, n); return 0; }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
Similar to the for loop, we can use the while loop to iterate the array. In this case, it's also like this
The size of the array must be known or determined.
while(condition) { statement(s); }
#include <iostream> #include <set> using namespace std; // displays elements of an array using for loop void solve(int arr[], int n){ int i = 0; while (i < n) { cout << arr[i] << ' '; i++; } cout << endl; } int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << "Values in the array are: "; solve(arr, n); return 0; }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
for (datatype val : array_name) { statements }
#include <iostream> #include <set> using namespace std; int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; //using for each loop cout << "Values in the array are: "; for(int val : arr) { cout << val << ' '; } cout << endl; return 0; }
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
This article describes various methods of traversing arrays in C. The main methods include:
drawback of the first two methods is that the size of the array has to be known beforehand, But if we use for-each loop, this problem can be alleviated. for-each loop supports all STL container and easier to use.The above is the detailed content of C++ program to iterate over array. For more information, please follow other related articles on the PHP Chinese website!