9.3 - First initial

Problem

Write a procedure that will receive an array of forenames and display each initial.

Example run

Initials
A
B
C

Array

forenames = ["Anna", "Bob", "Chris"]

 

1 Display initials IN names
OUT  
1.1 display “Initials”
1.2 for i from 0 to length of names -1
1.3         display current name substring[0:1]

 

 

# Main
names = ["Anna", "Bob", "Chris"]
display_initials(names)
def display_initials(names):
    print("Initials")
    for i in range(len(names)):
        print(names[i][0:1])

# Main
names = ["Anna", "Bob", "Chris"]
display_initials(names)
"""
Procedure: display_initials(names)
----------------------------------
This procedure takes an array of names as a parameter.

It loops through each name in the array.
The line:
    print(names[i][0:1])
means:
- First choose one string from the array with names[i].
- Then take the substring from position 0 up to position 1.
- This gives exactly the first letter of that name.
The procedure prints out the initials (first letters) of all the names.
"""
def display_initials(names):
    print("Initials")
    # loop through each position in the array
    for i in range(len(names)):
        # take the substring from character 0 up to 1 of this name
        # this gives just the first letter
        print(names[i][0:1])


"""
Main program
------------
1. Create an array of names.
2. Call the procedure display_initials(names)
   and pass the array as the parameter.
"""
# Main
names = ["Anna", "Bob", "Chris"]
display_initials(names)

Extension

Update the procedure to accept two arrays for forenames and surnames. Display the initials from each as shown.

1 Display initials IN forenames, surnames
OUT  
forenames = ["Anna", "Bob", "Chris"]
surnames = ["Boyd", "Cooper", "Davis"]

 

Initials
AB
BC
CD

Target

Access a substring within an array