The use of arrays (or equivalent) when solving problems: one-dimensional (1D)
2.2.3 Additional Programming Techniques
Practise exam questionsAdditional Programming Techniques — Note 6 of 12
Arrays as fixed length or static structures
A one-dimensional (1D) array is a data structure that stores a fixed-size collection of elements of the same data type under a single name. Each element is accessed using an index (position number), starting from 0. Arrays are static, meaning their size cannot change once they are created.
array names[5] creates an array with 5 elements (index 0 to 4).names[0] = "Alice" puts "Alice" at position 0.for count = 0 to theTeam.length - 1.len(scores) gives the number of items, so for i in range(len(scores)): visits every index. This is safer than hard-coding range(3), which breaks if the array changes size.found = False before the loop, set it to True inside the loop when a match is found, then report the result AFTER the loop has finished.theTeam[count], NOT theTeam[i] if the counter is called count.range(6) gives 0-5.theTeam.length returns the number of elements. To loop from 0, use for i = 0 to theTeam.length - 1.scores = [3, 6, 6, 9, 2, 8] → scores[2] = 6 (third element, 0-indexed). Remember arrays are ZERO-INDEXED.else: print("Not found") inside the loop prints 'Not found' once for every item that doesn't match.for count = 0 to theTeam.length - 1; if theTeam[count] == studentName then return True. Use the COUNTER as the array INDEX.# Create and access a 1D array (list in Python)
scores = [10, 20, 30, 40, 50]
print(scores[0]) # 10 (first element)
print(scores[2]) # 30 (third element)
scores[1] = 25 # Update second element
# Loop through the array
for i in range(len(scores)):
print("Index " + str(i) + ": " + str(scores[i]))scores = [4, 7, 8] # define an array
print(scores[1]) # 7: index 1 is the SECOND element
for i in range(len(scores)): # index 0, 1, 2
print(scores[i]) # print each item
scores[0] = 10 # replace the first element (index 0) with 10scores = [4, 7, 8]
total = 0 # running total
for i in range(len(scores)): # loop through each index
total += scores[i] # add each score to the total
average = total / len(scores)
print("Total:", total) # Total: 19
print("Average:", average) # Average: 6.333...scores = [12, 7, 5, 10, 3, 2, 7]
target = 7 # the value we are searching for
found = False # flag: nothing found yet
for i in range(len(scores)):
if scores[i] == target:
found = True # set the flag when a match is found
if found: # checked AFTER the loop
print("Found")
else:
print("Not found")scores = [12, 5, 10, 6, 7, 12]
target = 12
count = 0 # how many times the target appears
for i in range(len(scores)):
if scores[i] == target:
count += 1 # increase the count on each match
print("Appears", count, "times") # Appears 2 timesReady to test yourself?
Practise 2.2.3 questions