Traversing a 1D Array

Traversing a 1D Array is the process of looping through an array and assigning or using each index within the array. This is very common – almost expected – within the National 5 assignment and exam. Traversing a 1D Array can also be merged with the running total standard algorithm, where the array is looped through and each index of the array is added to a total.

Key Points

The act of looping through an array.

Very common within assignments.

Can be used in combination with Running Totals.

What does Traversing a 1D Array look like?

Traversing a 1D Array requires an array of data to be looped through, and each index of the array to be used in some way.

  1. Array is defined and assigned
  2. Loop through the length of the array
    1. For each index in the array, perform an action on the index

Below are three examples of how this may look.

word = "Hello"

print(len(word))

In this example, an empty array of names is created. The code then traverses through the 1D array, and for each index, the user can enter a name. This name is then stored at that index of the array.

names = [str]*10

for i in range(len(names)):
    names[i] = str(input("Enter a name: "))

In this example, the array of colours already exists. Using the traversing a 1D array standard algorithm, the length of the array is looped and each index is printed for the user.

colours = ["Pink", "Blue", "Green", "Red", "Yellow", "Purple", "Black", "White"]

for i in range(len(colours)):
    print(colours[i])

In this example, the traversing a 1D array standard algorithm is combined with a running total. Both the 1d array and total are predefined before the fixed loop starts. The array is then looped, and each index is added to the total inside the loop.

scores = [7, 10, 3, 0, 5, 3, 6, 1]
total = 0

for i in range(len(scores)):
    total = total + scores[i]

National 5 Requirements

You should be able to implement the traversing a 1D array standard algorithm into a solution.