3.2 Oldest person
You have two parallel arrays: one stores names and the other stores ages. Find the oldest age and display the name of the pupil who has that age.
names = ["Jane", "John", "Jess", "Ava"] ages = [14, 19, 15, 17]
Oldest person: John (age 19)
set names to ["Jane", "John", "Jess", "Ava"]
set ages to [14, 19, 15, 17]
set max_age to first value in ages array
set max_pos to 0
loop through ages starting at position 1
if age at current position is greater than max_age
set max_age to age at current position
set max_pos to current position
print "Oldest person:", name at max_pos, "(age", max_age, ")"
names = ["Jane", "John", "Jess", "Ava"]
ages = [14, 19, 15, 17]
max_age = ages[0]
max_pos = 0
for i in range(1, len(ages)):
if ages[i] > max_age:
max_age = ages[i]
max_pos = i
print("Oldest person:", names[max_pos], "(age", max_age, ")")
# Parallel arrays: names and matching ages at the same positions
names = ["Jane", "John", "Jess", "Ava"]
ages = [14, 19, 15, 17]
# Start with the first age as the current maximum, and remember its position
max_age = ages[0]
max_pos = 0
# Check from position 1 because position 0 is already used as the starting value
for i in range(1, len(ages)):
# If the age at the current position is greater than the current maximum
if ages[i] > max_age:
# Update the maximum age and store the position (to link back to the name)
max_age = ages[i]
max_pos = i
# Use the stored position to get the matching name from the names array
print("Oldest person:", names[max_pos], "(age", max_age, ")")
Extension
Update the program so that it not only finds and displays the oldest person, but also finds and displays the youngest.
Oldest person: John (age 19) Youngest person: Jane (age 14)