The use of arrays (or equivalent) when solving problems: two-dimensional arrays(2D)
2.2.3 Additional Programming Techniques
Practise exam questionsAdditional Programming Techniques — Note 7 of 12
Use of 2D arrays to emulate database tables of a collection of fields, and records
A two-dimensional (2D) array is an array of arrays, like a table or grid with rows and columns. You access elements using two indices: the first selects the row and the second selects the column. 2D arrays can be used to emulate database tables where each row is a record and each column is a field.
array[row, column] (OCR ERL) or array[row][column] (Python).journeys[3,1] = "3.5" (row 3, column 1).int() or float()) when stored as strings.scores[row][column]: the first index picks the row (the week), the second picks the column (the day). scores[1][2] is week 2, Wednesday.total = total + float(events[i,3]).events[i,0] == date, then add int(events[i,3]) or float(events[i,3]) to total.# 2D array (list of lists in Python)
seating = [
["Alice", "Bob"],
["Cara", "Dan"]
]
print(seating[0][1]) # "Bob" (row 0, col 1)
print(seating[1][0]) # "Cara" (row 1, col 0)
# Loop through all elements
for row in range(len(seating)):
for col in range(len(seating[row])):
print(seating[row][col], end=" ")
print() # New line after each row# Each row is a week; each column is a day (0 = Monday ... 4 = Friday)
scores = [
[4, 7, 8, 6, 5], # Week 1
[6, 5, 9, 4, 3], # Week 2
[10, 3, 6, 7, 2], # Week 3
[7, 8, 5, 6, 9] # Week 4
]
# Week 2 (row 1), Wednesday (column 2)
print(scores[1][2]) # 9
# Every score: outer loop = weeks, inner loop = days
for i in range(4):
for j in range(5):
print("Week", i + 1, "Day", j, "Score:", scores[i][j])# uses the scores array defined above
total = 0
count = 0
for i in range(4): # each week
for j in range(5): # each weekday
total += scores[i][j]
count += 1
average = total / count
print("Monthly total:", total)
print("Monthly average:", average)# uses the scores array defined above
for i in range(4): # for each week (row)
week_total = 0 # reset for EVERY week
for j in range(5): # for each day in that week
week_total += scores[i][j]
week_average = week_total / 5
print("Week", i + 1, "Total:", week_total, "Average:", week_average)# uses the scores array defined above
for j in range(5): # for each day (column)
day_total = 0 # reset for EVERY day
for i in range(4): # for each week
day_total += scores[i][j]
day_average = day_total / 4
print("Day", j, "(0 = Mon) Total:", day_total, "Average:", day_average)Ready to test yourself?
Practise 2.2.3 questions