Exercises for Lesson 2
Exercise 1: Conditionals and loops in Kotlin
1a: Conditionals
Predict the output of the following code:
val x: Int = 4
val y: Int = 10
val z: Int = 8
if (x != y) {
println(2+x)
} else {
println(y-x)
}
when {
x > y -> println("a")
x == y -> println("b")
y > z -> println("c")
x < z -> println("d")
else -> println("e")
}
z += 2
if (y == z) {
println("They're the same now!")
}1b: Loops
Predict the output of the following code:
for (x: Int in 1..5) {
println(x * x)
}
for (x: Int in 2..<8 step 2) {
println(x)
}
for (x: Int in 10 downTo 1 step 3) {
println(x)
}
for (s: String in listOf("apple", "banana", "canteloupe")) {
println("String: $s")
}
var y = -10
while (y > 0) {
println(y)
y -= 4
}
var z = -10
do {
println(z)
z -= 4
} while (z > 0)Exercise 2: Functions
Predict the output of the following program:
fun greet() {
print("What is your name? ")
val name: String? = readLine()
println("Hi $name!")
}
fun mult(x: Int, y: Int) {
println(x * y)
}
fun mult2(x: Int, y: Int): Int {
return x * y
}
fun main() {
greet()
val res = mult(2, 3)
println(res)
val res2 = mult2(3, 4)
println(res2)
}