Start learning free

LESSON 205 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in Swift: Looping Over Several Students

Practice Read the full explanation

Combine lists, loops, and conditionals to print a letter grade for each student in a class.

You start with:

let names = ["Alice", "Bob", "Carol", "Dan"]
let scores = [92, 78, 85, 67]

Build:

Alice: A
Bob: C
Carol: B
Dan: D

Rules:

  • Loop over the indices of the students (names.indices) so you can read the name and the score at the same position.
  • Use the same scale as V3: 90+ A, 80-89 B, 70-79 C, 60-69 D, below 60 F.
  • On each iteration print the name, a colon and a space, then the grade, for example Alice: A.

Use Swift arrays and for i in 0..<names.count.

let names = ["Alice", "Bob", "Carol", "Dan"]
let scores = [92, 78, 85, 67]

for i in names.indices {
    let score = scores[i]
    var grade = ""
    if score >= 90 {
        grade = "A"
    } else if score >= 80 {
        grade = "B"
    } else if score >= 70 {
        grade = "C"
    } else if score >= 60 {
        grade = "D"
    } else {
        grade = "F"
    }
    print("\(names[i]): \(grade)")
}

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in Swift, explained

    Problem overview

    Two parallel arrays describe a class: names holds four students and scores holds their scores, so position 2 in both arrays refers to Carol. The program prints one line for each student, in the form Alice: A, using the same grading scale as the previous version: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, anything lower is F.

    For the starting data the output is:

    Alice: A
    Bob: C
    Carol: B
    Dan: D
    

    Approach: one index for two arrays

    Version 3 graded a single score. To grade four, the same ladder has to run four times, once per student. A for loop does the repeating; the ladder goes inside it unchanged.

    The only new problem is that the name and the score live in different arrays. The link between them is their position. If the loop variable is a position, names[i] and scores[i] always describe the same student. That is why the lesson loops over names.indices rather than over the names themselves: the loop yields positions, and you read both arrays with each one.

    Step by step

    1. Write the loop. for i in names.indices visits 0, 1, 2 and 3. Add the closing brace immediately and put the rest inside it.
    2. Read this student's score into let score with scores[i]. It is a constant because it doesn't change during one pass.
    3. Declare var grade = "" inside the loop. It is a var because the ladder assigns it. Declaring it inside means each student starts fresh.
    4. Build the ladder in four more steps: if score >= 90 for A, then else if tests for 80, 70 and 60, then a final else for F. The order matters for the same reason as before: each test relies on the higher ones having failed.
    5. Print inside the loop, after the ladder, so it prints once per student: the name from names[i], a colon and a space, then the grade.

    The solution in Swift

    let names = ["Alice", "Bob", "Carol", "Dan"]
    let scores = [92, 78, 85, 67]
    
    for i in names.indices {
        let score = scores[i]
        var grade = ""
        if score >= 90 {
            grade = "A"
        } else if score >= 80 {
            grade = "B"
        } else if score >= 70 {
            grade = "C"
        } else if score >= 60 {
            grade = "D"
        } else {
            grade = "F"
        }
        print("\(names[i]): \(grade)")
    }
    

    Swift specifics:

    • indices. For an array, indices is the range of valid positions, 0..<count. For the four names it is 0..<4. It adapts to the array's length, so adding a student to both arrays needs no change to the loop.
    • Interpolation with a subscript. "\(names[i]): \(grade)" puts an expression with brackets inside the string. Anything valid in Swift can sit between the parentheses.
    • Scope. score and grade exist only inside the loop body. Each pass creates them again.
    • Arrays are bounds-checked. Reading a position outside the array stops the program with a run-time error; Swift never reads stray memory.

    Tracing the first two students

    On the first pass i is 0. score is 92, which is at least 90, so grade becomes "A" and the program prints Alice: A. The remaining branches of the ladder are skipped.

    On the second pass i is 1 and score is 78. The tests for 90 and 80 fail, the test for 70 passes, and grade becomes "C", so the output is Bob: C. Because grade is declared inside the loop, the "A" from the first pass is gone: the variable starts as empty text again.

    Carol (85) and Dan (67) follow the same path through the ladder and give B and D. The loop ends after the last position, 3, and the program has printed four lines, one for each name, in the order of the array.

    The important point is that the grading logic didn't change from the previous version. Only the surrounding loop is new, and it supplies a different score each time.

    Edge cases and common mistakes

    • Arrays of different lengths. If scores were shorter than names, scores[i] would crash on the first missing position. The loop assumes the arrays line up, and so does this lesson's data.
    • An empty class. With two empty arrays, indices is empty, the body never runs, and nothing is printed.
    • Putting print outside the loop. It would run once, after the loop, and i would not exist there.
    • Declaring grade before the loop. It would still work here because every pass assigns it, but declaring it inside keeps one student's result from leaking into the next.
    • Boundaries. Scores of exactly 90, 80, 70 and 60 belong to the higher grade, so every test uses >=.

    Testing

    These outputs come from running the solution on other data.

    • ["Eve", "Finn"] with scores [59, 90] prints Eve: F and Finn: A.
    • Two empty arrays print nothing.
    • The starting data prints the four lines shown at the top.

    The next version builds on this program.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free