Data Structures and Algorithms
In this tutorial we will learn to traverse an Array data structure in forward and reverse order.
To traverse an array means to access each of the element stored in the array. We can traverse an array in forward-direction (first element to last element) from left to right and in reverse-direction (last element to first element) from right to left.
In the following C++ code we are traversing the array from left to right i.e., from the first element to the last element. The array in this example has size 5.
#include<iostream>
using namespace std;
const int MAX = 5;
int main(void) {
int arr[MAX] = {1, 10, 5, 6, 3};
int i;
for (i = 0; i < MAX; i++) {
cout << "arr[" << i << "] = " << arr[i] << endl;
}
return 0;
}
Output
arr[0] = 1
arr[1] = 10
arr[2] = 5
arr[3] = 6
arr[4] = 3
Time complexity of forward traversal is O(n).
In the following C++ code we are traversing the array in reverse order i.e., from the last element to the first element. The array in this example also has size 5.
#include<iostream>
using namespace std;
const int MAX = 5;
int main(void) {
int arr[MAX] = {1, 10, 5, 6, 3};
int i;
for (i = MAX-1; i >= 0; i--) {
cout << "arr[" << i << "] = " << arr[i] << endl;
}
return 0;
}
Output
arr[4] = 3
arr[3] = 6
arr[2] = 5
arr[1] = 10
arr[0] = 1
Time complexity of reverse traversal is O(n).
ADVERTISEMENT