Bird
0
0
DSA Cprogramming

Array Traversal Patterns in DSA C

Choose your learning style9 modes available
Mental Model
Go through each item in the list one by one to see or use it.
Analogy: Like reading a book from the first page to the last page, looking at every word in order.
[0] -> [1] -> [2] -> [3] -> [4] -> null
 ↑
Dry Run Walkthrough
Input: array: [10, 20, 30, 40, 50]
Goal: Visit each element in the array from start to end and print it
Step 1: Start at index 0, read value 10
[0:10↑] -> [1:20] -> [2:30] -> [3:40] -> [4:50] -> null
Why: We begin at the first element to start traversal
Step 2: Move to index 1, read value 20
[0:10] -> [1:20↑] -> [2:30] -> [3:40] -> [4:50] -> null
Why: Move to next element to continue traversal
Step 3: Move to index 2, read value 30
[0:10] -> [1:20] -> [2:30↑] -> [3:40] -> [4:50] -> null
Why: Keep moving forward to visit all elements
Step 4: Move to index 3, read value 40
[0:10] -> [1:20] -> [2:30] -> [3:40↑] -> [4:50] -> null
Why: Continue until last element
Step 5: Move to index 4, read value 50
[0:10] -> [1:20] -> [2:30] -> [3:40] -> [4:50↑] -> null
Why: Last element visited to complete traversal
Result:
[0:10] -> [1:20] -> [2:30] -> [3:40] -> [4:50] -> null
Printed values: 10 20 30 40 50
Annotated Code
DSA C
#include <stdio.h>

void traverseArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        // print current element
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    traverseArray(arr, size);
    return 0;
}
for (int i = 0; i < size; i++) {
loop through each index from start to end
printf("%d ", arr[i]);
print the current element at index i
OutputSuccess
10 20 30 40 50
Complexity Analysis
Time: O(n) because we visit each of the n elements once
Space: O(1) because we use only a fixed amount of extra space
vs Alternative: Compared to random access, traversal is simple and direct with no extra cost
Edge Cases
empty array
loop does not run, nothing is printed
DSA C
for (int i = 0; i < size; i++) {
array with one element
prints the single element correctly
DSA C
for (int i = 0; i < size; i++) {
When to Use This Pattern
When you need to look at or use every item in a list one by one, use array traversal to visit each element in order.
Common Mistakes
Mistake: Using <= instead of < in the loop condition causing out-of-bounds access
Fix: Change loop condition to i < size to stay within array limits
Mistake: Starting loop index at 1 instead of 0, skipping first element
Fix: Start loop index at 0 to include the first element
Summary
It visits each element in an array one by one.
Use it when you want to process or read all items in order.
Remember to start at index 0 and stop before the array size.