Exercises for Lesson 3
Exercise 1: Representing tasks
For this exercise, you will write a class named Task allows us to associate something to do (e.g., study for Quiz 1) and with whether it has been completed (true or false).
You should store the text of the task to complete as a String and the completion status as a Boolean.
Part 1a: first on paper
Try to write out an implementation on paper. Check with a neighbor. Keep in mind that a correct implementation can be extremely short!
Part 1b: coding it up
Now try it! Type up your class definition in Kotlin. Here is a main function you can use to test your implementation:
fun main() {
val t1 = Task("Study for Quiz 1")
val t2 = Task("Submit Assignment 1")
val t3 = Task("Prep for Friday's class", isComplete=true)
println(t1.name)
println(t2.isComplete)
println(t3.isComplete)
t2.isComplete = true
for (task: Task in listOf(t1, t2, t3)) {
println("Task ${task.name} is complete: ${task.isComplete}")
}
}Let’s say you name your file Task.kt. Remember that you can compile it from the terminal with kotlinc:
kotlinc Task.ktand then execute it with kotlin:
kotlin TaskKt.classHere is the output I get when running main:
Study for Quiz 1
false
true
Task Study for Quiz 1 is complete: false
Task Submit Assignment 1 is complete: true
Task Prep for Friday's class is complete: truePart 1c: extending your class
Did you finish early? If so, think about what other methods may be handy for a Task, type them up, and then add code to main to verify their functionality!
Exercise 2: Counting steps
For each of the following Kotlin code fragments, predict 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")
}
}Exercise 3: Counting steps as a function
For each of the following Kotlin code fragments, predict 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")
}
}