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!")
}
val a: Int = when {
x > y -> 4
x > z -> 10
else -> -5
}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 mult3(x: Int, y: Int = 4): Int {
return mult2(x, y)
}
fun main() {
greet()
val res = mult(2, 3)
println(res)
val res2 = mult2(3, 4)
println(res2)
val res3 = mult3(10)
println(res3)
}
Exercise 3: Pet
Your goal is to write a class named Pet, which allows us to store information about our pets.
The Pet class should have the following methods:
Pet(name, age, kind)constructor: takesname(a string),age(an integer, in years), andkind(a string, like"dog"or"cat"), with all three as instance variablesrename(newName): updates the name of a pet; returns nothingupdateAge(): updates the age when the pet has a birthday; returns nothing
Create a file Pet.kt and put your code there. To get you started, here is a main function you can use to test part of your implementation:
fun main() {
// Make a few Pet objects
val lulu: Pet = Pet("Lulu", 13, "cat")
val hobbes: Pet = Pet("Hobbes", 13, "cat")
val cheddar: Pet = Pet("Cheddar", 1, "dog")
val mal: Pet = Pet("Marshmallow", 1, "dog")
// Print some info
println("Marshmallow is currently ${mal.age} year(s) old, and Cheddar is ${cheddar.age}.")
print("The cats are: ")
for (pet: Pet in listOf(lulu, hobbes, cheddar, mal)) {
if (pet.kind == "cat") {
print("${pet.name} ")
}
}
println()
// Mal has a birthday this fall!
mal.updateAge()
println("This fall Mal will be older! (${mal.age} year(s))")
}