Array Traversal
Table of Contents + β
Say you have a list of marks for a class. You want to print every mark. Or maybe add them all up. You canβt do that by touching one element at a time by hand. You need a way to walk through the whole array, element by element. That walk is called traversal. That is what we will learn here.
π What is Array Traversal?
Traversing an array means visiting every element exactly once. Usually we do this with a loop. The loop starts at one end and moves to the other.
Think of a postman delivering letters on a street. He starts at the first house and drops a letter. Then he moves to the next house. He keeps going till the last house. He visits each house once. That is exactly what traversal does with array elements.
Once we can visit each element, we can do useful things while we are there:
- Print each element with its index.
- Add up all the elements to get a sum.
- Search for a value or find the largest one.
π§ Forward and Backward Traversal
There are two simple directions we can walk through an array. The direction just decides where we start and where we stop.
- Forward traversal starts at the first element (index
0) and moves to the last element. This is the most common one. - Backward traversal starts at the last element (index
size - 1) and moves back to the first element. We use this when we need the elements in reverse order.
Here is how a forward walk looks on an array of five numbers. We touch index 0, then 1, and so on till the end.
Index: 0 1 2 3 4Value: [10, 20, 30, 40, 50] β start ββββββββββββΊ endA backward walk is the same array, just read from the other side.
Index: 0 1 2 3 4Value: [10, 20, 30, 40, 50] β end ββββββββββββ startIndexes start at 0
In almost all languages, the first element sits at index 0, not 1. So an array with 5 elements has valid indexes from 0 to 4. A forward loop runs from 0 to size - 1.
π οΈ Steps to Traverse an Array (Forward)
Before we write code, let us understand the steps. A forward traversal is just a loop with a counter.
- Create a function
traverseForward(array, size). - Inside the function, start a loop with a counter
iset to0. - Keep looping while
iis less thansize. - On each turn, read
array[i]and print it along with the indexi. - Increase
iby1so the next turn moves to the next element. - The loop stops when
ireachessize. That means every element has been visited.
So the loop counter i is doing the walking. It points at one element at a time, from the first to the last.
Code Examples to Traverse an Array Forward
Now let us see how to print each element with its index in different programming languages.
Program to traverse an array forward in Python
# function to traverse the list from start to enddef traverse_forward(arr): # loop counter i walks from 0 to len(arr) - 1 for i in range(len(arr)): # print each element with its index print(f"Index {i} -> {arr[i]}")
def main(): arr = [10, 20, 30, 40, 50] traverse_forward(arr)
if __name__ == "__main__": main()The output of the above code will be:
Index 0 -> 10Index 1 -> 20Index 2 -> 30Index 3 -> 40Index 4 -> 50Complexity Analysis for Forward Traversal
Time Complexity:
- O(n) - We visit each of the n elements exactly once, so the work grows in a straight line with the number of elements. Space Complexity:
- O(1) - We only use a fixed amount of extra space for the loop counter, no matter how big the array is.
π Steps to Traverse an Array (Backward)
A backward traversal is the same idea. We just flip the start and the stop. The counter starts at the last index and counts down.
- Create a function
traverseBackward(array, size). - Inside the function, start a loop with a counter
iset tosize - 1, which is the last index. - Keep looping while
iis greater than or equal to0. - On each turn, read
array[i]and print it along with the indexi. - Decrease
iby1so the next turn moves one step back. - The loop stops when
igoes below0. That means we have reached past the first element.
Code Examples to Traverse an Array Backward
Now let us print the same array in reverse order.
Program to traverse an array backward in Python
# function to traverse the list from end to startdef traverse_backward(arr): # loop counter i walks from len(arr) - 1 down to 0 for i in range(len(arr) - 1, -1, -1): # print each element with its index print(f"Index {i} -> {arr[i]}")
def main(): arr = [10, 20, 30, 40, 50] traverse_backward(arr)
if __name__ == "__main__": main()The output of the above code will be:
Index 4 -> 50Index 3 -> 40Index 2 -> 30Index 1 -> 20Index 0 -> 10Complexity Analysis for Backward Traversal
Time Complexity:
- O(n) - Just like forward traversal, we still visit each of the n elements exactly once. The direction does not change the amount of work. Space Complexity:
- O(1) - We only use a fixed amount of extra space for the loop counter.
β Sum of All Elements (Traversal in Action)
Traversal is not just for printing. Most of the time we visit each element to compute something. A classic example is adding up all the elements to get their sum.
The idea is simple. We keep a variable sum that starts at 0. Then we traverse the array forward. On each element we add its value to sum. When the loop ends, sum holds the total.
Here are the steps:
- Create a function
sumOfElements(array, size). - Set a variable
sumto0. - Traverse the array forward with a loop counter
i. - On each turn, add
array[i]tosum. - After the loop ends, return
sum.
Code Examples to Sum All Elements of an Array
Now let us add up the numbers 10, 20, 30, 40, 50 while we traverse.
Program to sum all elements of an array in Python
# function to add up every element of the listdef sum_of_elements(arr): total = 0 # traverse forward and add each element to total for i in range(len(arr)): total = total + arr[i] return total
def main(): arr = [10, 20, 30, 40, 50] total = sum_of_elements(arr) print(f"Sum of all elements = {total}")
if __name__ == "__main__": main()The output of the above code will be:
Sum of all elements = 150Complexity Analysis for Sum of Elements
Time Complexity:
- O(n) - We traverse the whole array once, touching each of the n elements a single time to add it. Space Complexity:
- O(1) - We only keep one extra variable
sum, so the extra space stays the same no matter how big the array is.
π Time and Space Complexity for Traversal
Every traversal we saw does the same amount of work. It walks the array once, so the cost is always linear in the number of elements.
| Traversal Type | Time Complexity | Space Complexity |
|---|---|---|
| Forward Traversal | O(n) | O(1) |
| Backward Traversal | O(n) | O(1) |
| Sum of Elements | O(n) | O(1) |
β οΈ Common Mistakes to Avoid
A few small slips trip up beginners when they traverse arrays. Watch out for these:
- Looping while
iis less than or equal tosizeinstead of less thansize. The last valid index issize - 1. So this reads one step past the end and crashes or gives garbage. - Starting a backward loop at
sizeinstead ofsize - 1. The element at indexsizedoes not exist. - Forgetting to change the counter inside the loop. If you never do
i++ori--, the loop never ends. - Setting
sumto something other than0before adding. A wrong starting value gives a wrong total.
Off-by-one is the most common bug
The classic traversal mistake is an off-by-one error. You go one step too far or one step short. Always remember that an array of size elements has valid indexes from 0 to size - 1. Check your loopβs start and stop carefully.
π§© What Youβve Learned
You can now walk through any array in either direction. And you can do useful work while you are there. Hereβs what youβve picked up.
- β Traversal means visiting every element of an array exactly once, usually with a loop.
- β
Forward traversal runs from index
0tosize - 1, and backward runs fromsize - 1down to0. - β The loop counter is what does the walking. It points at one element at a time.
- β You can compute things during traversal, like summing all elements with a running total.
- β Traversal is O(n) in time and O(1) in extra space, since you touch each element once.
- β
The most common bug is off-by-one, so always keep valid indexes between
0andsize - 1.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does traversing an array mean?
Why: Traversal means walking through the array and visiting each element exactly once, usually with a loop.
- 2
For an array of size 5, what index does a forward traversal loop stop at?
Why: Valid indexes run from 0 to size - 1, so for size 5 the last visited index is 4.
- 3
What is the time complexity of traversing an array of n elements?
Why: We visit each of the n elements once, so the work grows in a straight line with n, which is O(n).
- 4
Where should a backward traversal loop counter start?
Why: The last valid index is size - 1, so a backward loop starts there and counts down to 0.
π Whatβs Next?
You can visit every element now. The next step is changing what is inside the array.
- Insert Element in Array shows how to add a new element at the start, a specific position, or the end.
- Delete Element from Array shows how to remove an element and shift the rest to fill the gap.