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
- Write the loop.
for i in names.indicesvisits 0, 1, 2 and 3. Add the closing brace immediately and put the rest inside it. - Read this student's score into
let scorewithscores[i]. It is a constant because it doesn't change during one pass. - Declare
var grade = ""inside the loop. It is avarbecause the ladder assigns it. Declaring it inside means each student starts fresh. - Build the ladder in four more steps:
if score >= 90for A, thenelse iftests for 80, 70 and 60, then a finalelsefor F. The order matters for the same reason as before: each test relies on the higher ones having failed. - 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,indicesis the range of valid positions,0..<count. For the four names it is0..<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.
scoreandgradeexist 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
scoreswere shorter thannames,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,
indicesis empty, the body never runs, and nothing is printed. - Putting
printoutside the loop. It would run once, after the loop, andiwould not exist there. - Declaring
gradebefore 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]printsEve: FandFinn: A.- Two empty arrays print nothing.
- The starting data prints the four lines shown at the top.
The next version builds on this program.
