Exercises for Lesson 6

Back to Lesson 6

Exercise 1: Counting steps

For each of the following Kotlin code fragments, indicate how many times the output statement is displayed.

for (x: Int in 1..4) {
    println(x)
}

for (x: Int in 1..<20) {
    if (x % 2 == 0) {
        println(x)
    }
}

for (x: Int in 0..<10) {
    for (y: Int in 1..x) {
        println("$x $y")
    }
}

Back to Lesson 6

Exercise 2: Counting steps as a function

For each of the following Kotlin code fragments, indicate how many times the output statement is displayed relative to n. What function could you use to describe this?

for (x: Int in 0..<n) {
    println(x)
}

for (x: Int in 0..<n) {
    for (y: Int in 0..<n) {
        if (x != y) {
            println("$x $y")
        }
    }
}

for (x: Int in 0..<n) {
    for (y: Int in x..<n) {
        println("$x $y")
    }
}

Back to Lesson 6