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:
i | names[i] | score | Printed line |
|---|---|---|---|
| 0 | Alice | 92 | Alice: A |
| 1 | Bob | 78 | Bob: C |
| 2 | Carol | 85 | Carol: B |
| 3 | Dan | 67 | Dan: 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
- Write the loop.
for i := 0; i < len(names); i++ {startsiat 0 and stops before it reaches the length. With four names,itakes the values 0, 1, 2 and 3. Write the closing brace immediately, and put the next steps inside it. - Read the score.
score := scores[i]copies this student's score into a variable with a short name, which keeps the ladder readable. - Declare
gradewithout a value.var grade stringcreates a string that starts as the empty string"". The ladder will fill it. - Build the ladder. Test from the top: 90 or more gives
"A", thenelse iffor 80, 70 and 60 give"B","C"and"D", and a finalelsegives"F". Because each test runs only when the ones above it were false, every test needs only a lower bound. - Print inside the loop, after the ladder. The line is
names[i], then": ", thengrade. 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 nowhile. The three-part forminit; condition; postis the counting loop, and it takes no parentheses. lenworks on slices.len(names)is 4, and the valid indexes are 0 to 3. The conditioni < len(names)stops at 3.- Zero values. A variable declared with
varand no value gets the zero value of its type:""for a string,0for an int,falsefor a bool. Here the ladder always assigns a letter, because the finalelsecatches 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
scoreorgrade. - Strings join with
+.names[i],": "andgradeare 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)makesireach 4, andscores[4]panics withindex 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 withpanic: 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,scoreandgradeare 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: DandIda: F. - Two empty slices print nothing.
