Given an integer array of size N, the task is to traverse and print the elements in the array.
Examples:
Input: arr[] = {2, -1, 5, 6, 0, -3}
Output: 2 -1 5 6 0 -3Input: arr[] = {4, 0, -2, -9, -7, 1}
Output: 4 0 -2 -9 -7 1
Ways to traverse the elements of an array in C++
Let's start discussing each of these methods in detail.
1. Using for Loop
Approach:
- Start a loop from 0 to N-1, where N is the size of the array.
- Use arr[i] to access each element of the array.
- Print every element using cout << arr[i] << endl;.
#include <bits/stdc++.h>
using namespace std;
void printArray(int* arr, int n){
int i;
cout << "Array: ";
for (i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
int main(){
int arr[] = {2, -1, 5, 6, 0, -3};
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
return 0;
}
Output
Array: 2 -1 5 6 0 -3
2. Using a for-each loop
for_each is a powerful STL algorithm to operate on range elements and apply custom-defined functions. It takes range starting and the last iterator objects as the first two parameters and the function object as the third one.
#include <bits/stdc++.h>
using namespace std;
void display(int x){
cout << x << " ";
}
int main(){
int arr[] = {2, -1, 5, 6, 0, -3};
cout << "Traverse using for_each: ";
for_each(arr, arr + 6, display);
return 0;
}
Output
Traverse using for_each: 2 -1 5 6 0 -3
3. Using range-based Loop
The range-based loop is the readable version of the for loop. The following code shows how to implement the above code using a range-based loop.
#include <bits/stdc++.h>
using namespace std;
int main(){
int arr[] = {2, -1, 5, 6, 0, -3};
for (const auto &var : arr) {
cout << var << " " ;
}
return 0;
}
Output
2 -1 5 6 0 -3