Problem overview
Version 3 graded one score. Now there is a whole class: two arrays hold the students' names and their scores, and the program prints one line per student with the letter grade, using the same scale as before (90 and up is A, 80 to 89 B, 70 to 79 C, 60 to 69 D, below 60 F). The starter code:
val names = arrayOf("Alice", "Bob", "Carol", "Dan")
val scores = intArrayOf(92, 78, 85, 67)
The student at position 0 is Alice with 92, and so on. The expected output is:
Alice: A
Bob: C
Carol: B
Dan: D
Approach
The two arrays are parallel: the name at index i and the score at index i belong to the same student. The task is to repeat the grading ladder from version 3 once per student. That is a for loop over the indices, with the ladder inside it.
Using the index, rather than looping over the names directly, is what keeps the two arrays in step: the same i reads names[i] and scores[i]. The loop runs i from 0 up to, but not including, names.size.
This version reuses the ladder you wrote before, so the new ideas are the arrays and the loop. The grading logic itself doesn't change: it only moves inside a loop body.
Step by step
- Write the loop.
for (i in 0 until names.size)makesitake 0, 1, 2 and 3. Close its brace at once; everything else goes inside it. - Read this student's score. A
valnamedscoregetsscores[i]. Declaring it inside the loop gives each pass a fresh value. - Declare the grade without a value.
val grade: Stringreserves the name. Kotlin needs the type written out, since there is nothing to infer it from yet. - Start the ladder.
if (score >= 90)assigns"A". - Add the middle branches.
else if (score >= 80)gives"B",else if (score >= 70)gives"C", andelse if (score >= 60)gives"D". Each test relies on the ones above it having failed. - Finish with
else. It assigns"F", so every path givesgradea value. - Print inside the loop. After the ladder, print the name, a colon and a space, then the grade. Because it sits inside the loop, it runs once per student and makes the four lines.
The solution in Kotlin
val names = arrayOf("Alice", "Bob", "Carol", "Dan")
val scores = intArrayOf(92, 78, 85, 67)
for (i in 0 until names.size) {
val score = scores[i]
val 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"
}
println(names[i] + ": " + grade)
}
Kotlin details worth knowing:
- Two kinds of array.
arrayOf("Alice", ...)makes anArray<String>, andintArrayOf(92, ...)makes anIntArray, a compact array of primitive ints. Both use[i]for reading and have asize. 0 until nexcludesn.0 until 4gives 0, 1, 2, 3, while0..4would add a fifth index, 4. The statement also mentionsnames.indices, which is the same range as0 until names.sizeand avoids writing the bounds by hand.- Deferred initialisation with
val.val grade: Stringwithout a value is legal as long as the compiler can prove it is assigned exactly once on every path. The finalelseis what makes that provable. Remove it and the program no longer compiles: the compiler reportsvariable 'grade' must be initializedat the first use. - Joining text with
+.names[i] + ": " + gradebuilds the line. A string template,"${names[i]}: $grade", gives the same text.
Following the loop
Each pass of the loop is independent: it reads one score, runs the ladder from the top and prints one line.
| i | names[i] | scores[i] | First test that is true | Printed |
|---|---|---|---|---|
| 0 | Alice | 92 | score >= 90 | Alice: A |
| 1 | Bob | 78 | score >= 70 | Bob: C |
| 2 | Carol | 85 | score >= 80 | Carol: B |
| 3 | Dan | 67 | score >= 60 | Dan: D |
Nothing carries over from one pass to the next. score and grade are created again on every pass, which is why grade can be a val even though it holds a different letter each time: each pass has its own grade and assigns it once.
Edge cases and common mistakes
- Off by one.
0..names.sizeincludes the index 4, which is past the end of both arrays and throwsArrayIndexOutOfBoundsException. - Arrays of different length. If
scoreshas two entries andnameshas three, the loop prints the first two lines and then fails withArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2. The two arrays always need the same size. - Printing outside the loop. A
printlnafter the closing brace runs once, andgradeis not even visible there, because it was declared inside the loop body. - Boundary scores. The scores 90, 80, 70, 60 and 59 give A, B, C, D and F. A
>where>=belongs would move each boundary student down a grade. - Assigning twice. Because
gradeis aval, a second assignment in the same pass is a compile error. Avarwould allow it, which is why a ladder that assigns exactly once per path is a good fit forval. - No students. With empty arrays the loop body never runs, so the program prints nothing and does not crash.
Testing
Replace the data and run again. Using the names P, Q, R, S and T with the scores below shows the boundaries:
| scores | Output |
|---|---|
| 90, 80, 70, 60, 59 | P: A, Q: B, R: C, S: D, T: F (one per line) |
| 92, 78, 85, 67 | Alice: A, Bob: C, Carol: B, Dan: D |
| (empty) | no output |
