Start learning free

LESSON 204 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in Go: Grading Several Students in a Loop

Practice Read the full explanation

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

You start with:

names := []string{"Alice", "Bob", "Carol", "Dan"}
scores := []int{92, 78, 85, 67}

Build:

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

Rules:

  • Loop over the indices of the students (len(names)) 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 []string and []int slices with index loops.

names := []string{"Alice", "Bob", "Carol", "Dan"}
scores := []int{92, 78, 85, 67}

for i := 0; i < len(names); i++ {
    score := scores[i]
    var grade string
    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"
    }
    fmt.Println(names[i] + ": " + grade)
}

STEP 1 OF 9
    Ctrl + Enter to check

    GO · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in Go, explained

    Problem overview

    Version 3 graded one score. Version 4 grades a whole class, so the program needs a loop. The students are stored in two slices that line up by position: names[i] is a student and scores[i] is that student's score.

    names := []string{"Alice", "Bob", "Carol", "Dan"}
    scores := []int{92, 78, 85, 67}
    

    The scale is the one from version 3: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and below 60 is F. The program prints one line per student in the form name: grade:

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

    Approach: one counter for two slices

    The name and the score of a student sit at the same index in their slices, so one loop counter i can read both. The loop runs for i from 0 up to len(names) - 1. In each pass it takes the score at i, runs the letter-grade ladder from version 3 on it, and prints the name at i next to the result.

    Everything the loop needs for one student is declared inside the loop body: score, grade and the ladder. Each pass starts with new variables, so one student's grade can't leak into the next one's line.

    The four passes

    The loop body runs once for each student, and the printed lines match the passes:

    inames[i]scorePrinted line
    0Alice92Alice: A
    1Bob78Bob: C
    2Carol85Carol: B
    3Dan67Dan: D

    Bob's 78 is below 80, so the B test is false and the C test is true. The order of the students in the output is the order of the slices, because the loop walks them from index 0 to the end.

    Step by step

    1. Write the loop. for i := 0; i < len(names); i++ { starts i at 0 and stops before it reaches the length. With four names, i takes the values 0, 1, 2 and 3. Write the closing brace immediately, and put the next steps inside it.
    2. Read the score. score := scores[i] copies this student's score into a variable with a short name, which keeps the ladder readable.
    3. Declare grade without a value. var grade string creates a string that starts as the empty string "". The ladder will fill it.
    4. Build the ladder. Test from the top: 90 or more gives "A", then else if for 80, 70 and 60 give "B", "C" and "D", and a final else gives "F". Because each test runs only when the ones above it were false, every test needs only a lower bound.
    5. Print inside the loop, after the ladder. The line is names[i], then ": ", then grade. Being inside the loop, it runs once per student, giving four lines.

    The solution in Go

    names := []string{"Alice", "Bob", "Carol", "Dan"}
    scores := []int{92, 78, 85, 67}
    
    for i := 0; i < len(names); i++ {
        score := scores[i]
        var grade string
        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"
        }
        fmt.Println(names[i] + ": " + grade)
    }
    

    The code uses the fmt package. Some Go details are worth a closer look.

    • The only loop is for. Go has no while. The three-part form init; condition; post is the counting loop, and it takes no parentheses.
    • len works on slices. len(names) is 4, and the valid indexes are 0 to 3. The condition i < len(names) stops at 3.
    • Zero values. A variable declared with var and no value gets the zero value of its type: "" for a string, 0 for an int, false for a bool. Here the ladder always assigns a letter, because the final else catches every score that the other tests miss.
    • Scope. A variable declared inside the braces of the loop exists only there. Nothing after the loop can read score or grade.
    • Strings join with +. names[i], ": " and grade are all strings, so no conversion is needed, unlike with a number.

    Complexity

    Time is O(n) for n students: each one costs a constant number of comparisons. Extra space is O(1), since only i, score and grade are created, however long the slices are.

    Edge cases and common mistakes

    • Using <= in the loop condition. i <= len(names) makes i reach 4, and scores[4] panics with index out of range.
    • Slices of different lengths. The loop trusts len(names). With two names and one score, the program prints the first student and then stops with panic: runtime error: index out of range [1] with length 1. Go does not check that parallel slices match.
    • An empty class. With empty slices the loop body never runs, and the program prints nothing and doesn't fail.
    • Printing outside the loop. After the loop, i, score and grade are not available, and the code doesn't compile. Even with other variables, the line would print only once.
    • Boundary scores. A score of exactly 90 is an A and exactly 60 is a D. The tests use >= for that reason.

    Testing

    Try other classes, with a score on each boundary:

    • Names Eve, Finn, Gus, Hana and Ida with scores 90, 59, 100, 60 and 0 print Eve: A, Finn: F, Gus: A, Hana: D and Ida: F.
    • Two empty slices print nothing.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free