Start learning free

LESSON 204 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in Kotlin: Grading a Class with Arrays and 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:

val names = arrayOf("Alice", "Bob", "Carol", "Dan")
val scores = intArrayOf(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 arrayOf / intArrayOf and for (i in 0 until names.size).

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)
}

STEP 1 OF 9
    Ctrl + Enter to check

    KOTLIN · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in Kotlin, explained

    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

    1. Write the loop. for (i in 0 until names.size) makes i take 0, 1, 2 and 3. Close its brace at once; everything else goes inside it.
    2. Read this student's score. A val named score gets scores[i]. Declaring it inside the loop gives each pass a fresh value.
    3. Declare the grade without a value. val grade: String reserves the name. Kotlin needs the type written out, since there is nothing to infer it from yet.
    4. Start the ladder. if (score >= 90) assigns "A".
    5. Add the middle branches. else if (score >= 80) gives "B", else if (score >= 70) gives "C", and else if (score >= 60) gives "D". Each test relies on the ones above it having failed.
    6. Finish with else. It assigns "F", so every path gives grade a value.
    7. 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 an Array<String>, and intArrayOf(92, ...) makes an IntArray, a compact array of primitive ints. Both use [i] for reading and have a size.
    • 0 until n excludes n. 0 until 4 gives 0, 1, 2, 3, while 0..4 would add a fifth index, 4. The statement also mentions names.indices, which is the same range as 0 until names.size and avoids writing the bounds by hand.
    • Deferred initialisation with val. val grade: String without a value is legal as long as the compiler can prove it is assigned exactly once on every path. The final else is what makes that provable. Remove it and the program no longer compiles: the compiler reports variable 'grade' must be initialized at the first use.
    • Joining text with +. names[i] + ": " + grade builds 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.

    inames[i]scores[i]First test that is truePrinted
    0Alice92score >= 90Alice: A
    1Bob78score >= 70Bob: C
    2Carol85score >= 80Carol: B
    3Dan67score >= 60Dan: 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.size includes the index 4, which is past the end of both arrays and throws ArrayIndexOutOfBoundsException.
    • Arrays of different length. If scores has two entries and names has three, the loop prints the first two lines and then fails with ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2. The two arrays always need the same size.
    • Printing outside the loop. A println after the closing brace runs once, and grade is 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 grade is a val, a second assignment in the same pass is a compile error. A var would allow it, which is why a ladder that assigns exactly once per path is a good fit for val.
    • 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:

    scoresOutput
    90, 80, 70, 60, 59P: A, Q: B, R: C, S: D, T: F (one per line)
    92, 78, 85, 67Alice: A, Bob: C, Carol: B, Dan: D
    (empty)no output
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free