Algorithm Deep Dive Traversal

Traversing an Array Data Structure

One of the most common operation performed on array data structure is to traverse or visit all elements present inside it. This operation is also known as iterating an array. In this operation, we start from index 0, access the value, then move on to index 1, access the value, and so on until the last index.

Traversing an Array in forward direction

Below are basic implementations to initialize and traverse an array in forward direction. Note that there are simpler ways of traversing arrays based on the programming language used. But for this article, only the fundamental way of traversing an array using while loop is shown for all languages.

Loading code…

This is how the above code works:

  • Declare an integer array myArray containing a few values
  • Initialize length variable containing a number indicating the count of all elements present in the array
  • Initialize an index variable i and set it to starting index/position of the array, which is 0
  • We use a while loop to go through each index until it goes beyond the last position of the array
  • Visit/Print the current element using the expression myArray[i]
  • Increment the current index i in order to move to the next element. Expression normally used is i++ or i += 1 which are equivalent to i = i + 1
  • If the value of index variable is more than the index of last element in the array, stop the traversal

Traversing an Array in reverse direction

Below are basic implementations to initialize and traverse an array in reverse direction.

Loading code…

This is how the above code works:

  • Declare an integer array arr containing a few values
  • Initialize length variable containing a number indicating the count of all elements present in the array
  • Initialize an index variable i and set it to the ending index/position of the array, which is equal to length - 1
  • We use a while loop to go through each index until it becomes less than the first position
  • Visit/Print the current element using the expression myArray[i]
  • Increment the current index i in order to move to the next element. Expression used is i++ or i += 1 which are equivalent to i = i + 1
  • If the value of index variable is less than the first index (0), stop the traversal

Traversing an Array using for loop

In the above examples we used while loop to iterate/traverse the array. It is more clear and easy to understand at the beginning stages. But using a for loop to iterate through elements in an array is more compact.

Forward direction

Below are basic implementations to traverse an array using for loop.

Loading code…

Backward direction

Loading code…