Open In App

C++ Program To Traverse an Array

Last Updated : 19 Jul, 2022
Comments
Improve
Suggest changes
5 Likes
Like
Report

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 -3

Input: arr[] = {4, 0, -2, -9, -7, 1} 
Output: 4 0 -2 -9 -7 1 

There are three ways to traverse the elements of an array in C++:

  1. Using for loop.
  2. Using for_each loop.
  3. using range-based for loop.

Let's start discussing each of these methods in detail.

1. Using for Loop

Below is the approach for traversing an array using the for loop.

Approach:

A. Start a loop from 0 to N-1, where N is the size of the array.

for(i = 0; i < N; i++)


B. Access every element of the array with the help of

arr[index]


C. Print the elements.

cout << arr[i] << endl;

Below is the implementation of the above approach:


Output
Array: 2  -1  5  6  0  -3  

Time Complexity: O(n)

Auxiliary Space: O(1)

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. 
Below is the C++ program to implement the above approach:


Output
Traverse using array's data type2 -1 5 6 0 -3 
Traverse using auto keyword2 -1 5 6 0 -3 

Time Complexity: O(n)
Auxiliary Space: O(1)

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.


Output
2 -1 5 6 0 -3 

Time Complexity: O(n)
Auxiliary Space: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads