Table of Contents

    Array Traversal

    Programming Mastery

    Array Traversal

    Learn how to visit every element of an array one by one using loops, indexes, and clean traversal logic.

    What is Array Traversal?

    Array traversal means visiting each element of an array one by one.

    In simple words, when we move through an array from one element to another and access each value, it is called array traversal.

    Array traversal is the process of accessing every element of an array sequentially to perform an operation.

    During traversal, we may print values, calculate totals, search for an element, update values, find the highest value, or perform any other required operation.

    numbers = [10, 20, 30, 40, 50]
    
    Traversal means visiting:
    10 → 20 → 30 → 40 → 50

    Easy Real-Life Example

    Array Traversal as Walking Through Lockers

    Imagine there is a row of lockers. Each locker has a number. If you check each locker one by one from the first locker to the last locker, you are traversing the lockers.

    An array works in the same way. Each element has an index, and traversal means visiting each index one by one.

    Index:   0    1    2    3    4
    Value:  10   20   30   40   50

    Traversal starts from one index and moves to the next index until all required elements are visited.

    Why is Array Traversal Needed?

    Traversal is needed because most array operations require checking or processing each element.

    Array Traversal is Used For

    • Displaying all array elements.
    • Calculating the sum of numeric elements.
    • Finding the average value.
    • Searching for a specific value.
    • Finding the highest or lowest value.
    • Counting elements that match a condition.
    • Updating or modifying each element.
    • Copying elements from one array to another.
    • Checking whether all values satisfy a condition.
    • Processing data stored in arrays.
    Key Idea: If you want to work with every value in an array, you usually need traversal.

    General Logic of Array Traversal

    The basic idea of array traversal is:

    Traversal Steps

    • Start from the first index.
    • Access the current element.
    • Perform the required operation.
    • Move to the next index.
    • Repeat until the last required element is processed.
    FOR index FROM 0 TO length(array) - 1
        PROCESS array[index]
    END FOR

    Here, index moves through the array one position at a time.

    Array Traversal Flow

    START
      ↓
    Set index = 0
      ↓
    Check index < array length
      ↓
    Access array[index]
      ↓
    Perform operation
      ↓
    Increase index by 1
      ↓
    Repeat until all elements are visited
      ↓
    END

    Forward Traversal

    Forward traversal means visiting array elements from the first element to the last element.

    numbers = [10, 20, 30, 40, 50]
    
    Forward Traversal:
    10 → 20 → 30 → 40 → 50

    Pseudocode

    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50]
    
        FOR index FROM 0 TO length(numbers) - 1
            DISPLAY numbers[index]
        END FOR
    END ENTRY POINT

    Expected Output

    10
    20
    30
    40
    50

    Forward traversal is the most common type of array traversal.

    Reverse Traversal

    Reverse traversal means visiting array elements from the last element to the first element.

    numbers = [10, 20, 30, 40, 50]
    
    Reverse Traversal:
    50 → 40 → 30 → 20 → 10

    Pseudocode

    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50]
    
        FOR index FROM length(numbers) - 1 DOWN TO 0
            DISPLAY numbers[index]
        END FOR
    END ENTRY POINT

    Expected Output

    50
    40
    30
    20
    10

    Reverse traversal is useful when we need to process elements backward.

    Traversal Using a Loop

    Loops are commonly used for array traversal because they can repeat the same operation for every element.

    FOR index FROM 0 TO length(array) - 1
        DISPLAY array[index]
    END FOR

    The loop starts at index 0 and continues until the last index, which is usually length - 1.

    Important: For an array with n elements, valid indexes usually go from 0 to n - 1.

    Example 1: Display All Elements

    /*
    This program displays all elements of an array.
    */
    
    ENTRY POINT
        DECLARE fruits AS ARRAY = ["Apple", "Banana", "Mango", "Orange"]
    
        FOR index FROM 0 TO length(fruits) - 1
            DISPLAY fruits[index]
        END FOR
    END ENTRY POINT

    Expected Output

    Apple
    Banana
    Mango
    Orange

    Example 2: Display Elements with Index

    /*
    This program displays each element with its index.
    */
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50]
    
        FOR index FROM 0 TO length(numbers) - 1
            DISPLAY "Index " + index + " = " + numbers[index]
        END FOR
    END ENTRY POINT

    Expected Output

    Index 0 = 10
    Index 1 = 20
    Index 2 = 30
    Index 3 = 40
    Index 4 = 50

    Example 3: Calculate Sum of Array Elements

    Array traversal is commonly used to calculate totals.

    /*
    This program calculates the sum of all elements in an array.
    */
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50]
        DECLARE total AS INTEGER = 0
    
        FOR index FROM 0 TO length(numbers) - 1
            SET total = total + numbers[index]
        END FOR
    
        DISPLAY "Total: " + total
    END ENTRY POINT

    Expected Output

    Total: 150

    The loop visits each element and adds it to total.

    Example 4: Calculate Average

    /*
    This program calculates average marks using traversal.
    */
    
    ENTRY POINT
        DECLARE marks AS ARRAY = [85, 90, 78, 88, 92]
        DECLARE total AS INTEGER = 0
        DECLARE average AS DECIMAL = 0.0
    
        FOR index FROM 0 TO length(marks) - 1
            SET total = total + marks[index]
        END FOR
    
        SET average = total / length(marks)
    
        DISPLAY "Average Marks: " + average
    END ENTRY POINT

    Expected Output

    Average Marks: 86.6

    Example 5: Find Highest Value

    /*
    This program finds the highest value in an array.
    */
    
    ENTRY POINT
        DECLARE scores AS ARRAY = [45, 78, 92, 66, 81]
        DECLARE highest AS INTEGER = scores[0]
    
        FOR index FROM 1 TO length(scores) - 1
            IF scores[index] > highest THEN
                SET highest = scores[index]
            END IF
        END FOR
    
        DISPLAY "Highest Score: " + highest
    END ENTRY POINT

    Expected Output

    Highest Score: 92

    Here, traversal starts from index 1 because the first element is already stored in highest.

    Example 6: Find Lowest Value

    /*
    This program finds the lowest value in an array.
    */
    
    ENTRY POINT
        DECLARE prices AS ARRAY = [500, 250, 700, 150, 300]
        DECLARE lowest AS INTEGER = prices[0]
    
        FOR index FROM 1 TO length(prices) - 1
            IF prices[index] < lowest THEN
                SET lowest = prices[index]
            END IF
        END FOR
    
        DISPLAY "Lowest Price: " + lowest
    END ENTRY POINT

    Expected Output

    Lowest Price: 150

    Example 7: Search an Element

    Traversal is used to search whether a value exists in an array.

    /*
    This program searches for a target value in an array.
    */
    
    ENTRY POINT
        DECLARE names AS ARRAY = ["Aman", "Riya", "Sohan", "Meera"]
        DECLARE targetName AS TEXT = "Sohan"
        DECLARE isFound AS BOOLEAN = false
    
        FOR index FROM 0 TO length(names) - 1
            IF names[index] == targetName THEN
                SET isFound = true
                BREAK
            END IF
        END FOR
    
        IF isFound == true THEN
            DISPLAY targetName + " found"
        ELSE
            DISPLAY targetName + " not found"
        END IF
    END ENTRY POINT

    Expected Output

    Sohan found

    The loop stops early using BREAK when the target value is found.

    Example 8: Update Every Element

    Traversal can also be used to modify each element.

    /*
    This program adds 5 bonus marks to every student.
    */
    
    ENTRY POINT
        DECLARE marks AS ARRAY = [70, 75, 80, 85, 90]
    
        FOR index FROM 0 TO length(marks) - 1
            SET marks[index] = marks[index] + 5
        END FOR
    
        DISPLAY marks
    END ENTRY POINT

    Updated Array

    [75, 80, 85, 90, 95]

    Types of Array Traversal

    Traversal Type Direction Use Case
    Forward Traversal First element to last element. Printing, summing, searching, updating.
    Reverse Traversal Last element to first element. Printing reverse order, reverse checking.
    Partial Traversal Only selected part of array. Process elements from a specific range.
    Conditional Traversal Continues based on a condition. Stop when target is found.

    Common Operations During Traversal

    Operation What Happens During Traversal? Example
    Display Each value is printed. Print all names.
    Sum Each numeric value is added. Total marks.
    Average Total is calculated, then divided by length. Average score.
    Search Each value is compared with a target. Find a student name.
    Maximum Each value is compared with current highest. Highest score.
    Minimum Each value is compared with current lowest. Lowest price.
    Update Each value is changed based on logic. Add bonus marks.

    Traversal in a Two-dimensional Array

    For a two-dimensional array, traversal usually requires nested loops.

    The outer loop controls rows, and the inner loop controls columns.

    matrix = [
        [1, 2, 3],
        [4, 5, 6]
    ]
    
    FOR row FROM 0 TO numberOfRows(matrix) - 1
        FOR column FROM 0 TO numberOfColumns(matrix) - 1
            DISPLAY matrix[row][column]
        END FOR
    END FOR

    Expected Output

    1
    2
    3
    4
    5
    6

    Time and Space Complexity of Array Traversal

    In a simple one-dimensional array, traversal visits each element once.

    Metric Value Meaning
    Time Complexity O(n) The loop visits n elements.
    Space Complexity O(1) No extra large storage is needed for basic traversal.

    If an array has 5 elements, traversal visits 5 elements. If it has 100 elements, traversal visits 100 elements.

    Common Beginner Mistakes

    Mistakes

    • Starting traversal from index 1 instead of 0.
    • Using index <= length instead of index < length.
    • Trying to access an index outside the array range.
    • Forgetting that the last index is usually length - 1.
    • Not updating the loop counter in while-loop traversal.
    • Using the wrong direction in reverse traversal.
    • Forgetting to initialize variables such as total, highest, or isFound.
    • Using traversal when direct index access is enough.

    Better Habits

    • Start forward traversal from index 0.
    • Stop before index becomes equal to length.
    • Use length - 1 for the last valid index.
    • Use meaningful loop variables such as index.
    • Initialize result variables before traversal.
    • Use BREAK when searching and the target is found.
    • Test traversal with empty, one-element, and many-element arrays.
    • Use trace tables to debug traversal logic.

    Best Practices for Array Traversal

    Recommended Practices

    • Use loops to avoid repeated code.
    • Use clear variable names such as index, total, and target.
    • Keep traversal logic simple and readable.
    • Use forward traversal for normal processing.
    • Use reverse traversal only when reverse order is required.
    • Check array length before accessing elements.
    • Use nested loops for multidimensional arrays.
    • Use BREAK for early exit in search problems.
    • Do not access invalid indexes.
    • Test the first element, last element, and middle elements.

    Prerequisites Before Learning Array Traversal

    Students should already understand:

    Required Knowledge

    • Variables and constants.
    • Data types.
    • Input and output.
    • Loops and iteration.
    • Break statement.
    • One-dimensional array.
    • Multidimensional array basics.
    • Array indexes and length.
    • Basic comparison operators.

    Trace Table Example

    Let us trace the following array traversal:

    numbers = [10, 20, 30]
    total = 0
    
    FOR index FROM 0 TO length(numbers) - 1
        SET total = total + numbers[index]
    END FOR
    Iteration index numbers[index] total before total after
    1 0 10 0 10
    2 1 20 10 30
    3 2 30 30 60

    Final value of total is 60.

    Practice Activity: Predict the Output

    Predict the output of the following pseudocode.

    values = [2, 4, 6, 8]
    
    FOR index FROM 0 TO length(values) - 1
        DISPLAY values[index] * 2
    END FOR

    Your Answer

    Write the output here:
    
    ________________
    ________________
    ________________
    ________________

    Sample Answer

    4
    8
    12
    16

    Mini Quiz

    1

    What is array traversal?

    Array traversal is the process of visiting each element of an array one by one.

    2

    Why are loops used for array traversal?

    Loops are used because they can repeat the same operation for each element of the array.

    3

    What is forward traversal?

    Forward traversal means visiting elements from the first index to the last index.

    4

    What is reverse traversal?

    Reverse traversal means visiting elements from the last index to the first index.

    5

    What is the time complexity of simple array traversal?

    The time complexity is usually O(n) because every element is visited once.

    Interview Questions on Array Traversal

    1

    Define array traversal.

    Array traversal is the process of accessing every element of an array sequentially to perform an operation.

    2

    What are common operations performed during traversal?

    Common operations include displaying elements, calculating sum, finding average, searching, updating, and finding maximum or minimum values.

    3

    How do you traverse an array in reverse order?

    Start from the last index, which is usually length - 1, and move down to index 0.

    4

    Why is traversal important in arrays?

    Traversal is important because many array operations require checking or processing each element.

    5

    What is the difference between accessing and traversing an array?

    Accessing means reading one specific element using its index, while traversing means visiting many or all elements one by one.

    Quick Summary

    Concept Meaning
    Array Traversal Visiting each element of an array one by one.
    Forward Traversal Starts from the first element and moves to the last.
    Reverse Traversal Starts from the last element and moves to the first.
    Loop Role Repeats the operation for every element.
    Common Uses Display, sum, average, search, update, maximum, minimum.
    Time Complexity O(n) for simple traversal.
    Best Practice Use valid indexes and clean loop conditions.

    Final Takeaway

    Array traversal is one of the most important array operations. It allows programmers to visit each element and perform useful tasks such as printing, searching, updating, summing, and finding maximum or minimum values. In the Programming Mastery Course, students should understand traversal as the foundation for many future array-based algorithms and problem-solving techniques.