Get up to 80 % extra points for free! More info:

Lesson 5 - Loops in Kotlin

In the previous exercise, Solved tasks for Kotlin lesson 4, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on for and while loops in Kotlin instead of a thorough-full lesson? Here it is:

Using a for loop to execute code 3 times:

for (i in 1..3) { // runs 3 times in total
    println("Knock")
}
println("Penny!")

Accessing the loop control variable each iteration:

for (i in 1..10) {
    print("$i ") // prints the current value of the loop control variable
}

Nesting loops to work with tabular data:

println("Here's a simple multiplication table using nested loops:")
for (j in 1..10) {
    for (i in 1..10) {
        print("${i * j} ")
    }
    println()
}

Using a while loop when we don't know how many times the code is going to repeat:

println("Welcome to our calculator")
var goOn = "yes"
while (goOn == "yes") {
    println("Enter the first number")
    val a = readLine()!!.toDouble()
    println("Enter the second number:")
    val b = readLine()!!.toDouble()
    println("Choose one of the following operations:")
    println("1 - addition")
    println("2 - subtraction")
    println("3 - multiplication")
    println("4 - division")
    val choice = readLine()!!.toInt()
    var result: Double = 0.0
    when (choice) {
        1 -> result = a + b
        2 -> result = a - b
        3 -> result = a * b
        4 -> result = a / b
    }
    if ((choice > 0) && (choice < 5)) {
        println("Result: $result")
    } else {
        println("Invalid choice")
    }
    println("Would you like to make another calculation? [yes/no]")
    goOn = readLine()!!
}
println("Thank you for using our calculator.")

Notice using == to compare Strings.

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Kotlin lesson 4, we learned about conditions in Kotlin. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The for loop

The for loop has a determined fixed number of steps and allows us to go through all the items of some group of objects. The loop is executed for each item of the group, these executions are called iterations. The for loop syntax is the following:

for (variable in group)

First, let's have a look at how to do something more than once simply. For example, if we want to execute some code in a loop five times, we would generate a range of numbers from 1 to 5 and pass those to the loop. The code would be as follows:

for (i in 1..5) {

}

By doing this, the code in the loop is executed 5 times. In the variable i, there are the values from 1 in the first iteration to 5 in the last one.

If you know the for loop from other languages, you probably noticed that in Kotlin it's more like the foreach loop.

Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:

println("Knock")
println("Knock")
println("Knock")
println("Penny!")

However, using loops, we no longer have to copy the same code over and over:

for (i in 1..3) {
    println("Knock")
}
println("Penny!")

The output:

Knock
Knock
Knock
Penny!

Let's now take advantage of the fact that the variable is being incremented. Let's print numbers from one to ten. And since we don't want the text on separated lines in our console, we'll use the print() function instead.

for (i in 1..10) {
    print("$i ")
}

The reuslt:

1 2 3 4 5 6 7 8 9 10

We can see that the control variable has a different value after each iteration (step of the loop).

Now let's print a simple multiplication table that contains multiples of numbers from 1 to 10. All we need to do is to declare a loop from 1 to 10 and multiply the control variable with the current multiplier. It might look like this:

println("Simple multiplication table using loops:")
for (i in 1..10) {
    print("$i ")
}
println()
for (i in 1..10) {
    print("${i * 2}")
}
println()
for (i in 1..10) {
    print("${i * 3}")
}
println()
for (i in 1..10) {
    print("${i * 4}")
}
println()
for (i in 1..10) {
    print("${i * 5}")
}
println()
for (i in 1..10) {
    print("${i * 6}")
}
println()
for (i in 1..10) {
    print(("${i * 7}")
}
println()
for (i in 1..10) {
    print("${i * 8}")
}
println()
for (i in 1..10) {
    print("${i * 9}")
}
println()
for (i in 1..10) {
    print("${i * 10}")
}

The output:

Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

println("Here's a simple multiplication table using nested loops:")
for (i in 1..10) {
    for (j in 1..10) {
        print("${i * j} ")
    }
    println()
}

Makes a big difference, doesn't it? Obviously, we can't use i in both loops since they are nested. The variable j of the outer loop gains the values from 1 to 10. During each iteration of the loop, another inner loop with the variable i is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable j. After each time the inner loop terminates it's necessary to break the line, it is done by println().

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:

println("Exponent calculator")
println("===================")
println("Enter the base: ")
val a = readLine()!!.toInt()
println("Enter the exponent: ")
val n = readLine()!!.toInt()
var result = a
for (i in 1..n-1) {
    result = result * a
}
println("Result: $result")
println("Thank you for using our exponent calculator")

I'm sure we all know how powers (exponents) work. But just to be sure, let me remind that, e.g. 2^3 = 2 * 2 * 2. So, we compute an by multiplying the number a by the number a for n-1 times. Of course, the result must be stored in a variable. Initially, it'll have a value of a and this value will be gradually multiplying during the loop. We can see that our result variable in the loop body is normally accessible. If, however, we create a variable in a loop body, this variable will be no longer accessible after the loop terminates.

Exponent calculator{*T}
===================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator

Now, we know what some practical uses of the for loop are. Remember that it has a fixed amount of iterations. The loop variable is constant in every iteration, that means you can't change it (some languages allow it but it causes trouble).

The while loop

The while loop works differently, it simply repeats the commands in a block while a condition is true. The syntax of the loop is the following:

while (condition) {
    // commands
}

If you realized that the for loop can be simulated using the while loop, you are right :) The for loop is actually a special case of the while loop. However, the while loop is used for slightly different things. Typically, we call some method returning a logical true/false value, in the while loop parentheses. We could rewrite the original for-loop example to use the while loop instead:

var i = 1
while (i <= 10) {
    println(i)
    i += 1
}

But this is not an ideal example of using the while loop. Let's take our calculator from previous lessons and improve it a little bit. We'll add an ability to enter more math problems. The program will not end immediately, but it'll ask the user whether they wish to calculate another math problem. Let's remind the original version of the code (this is the version with when, but feel free to use the if-else version, it depends on you):

println("Welcome to our calculator")
println("Enter the first number:");
val a = readLine()!!.toDouble()
println("Enter the second number:")
val b = readLine()!!.toDouble()
println("Choose one of the following operations:")
println("1 - addition")
println("2 - subtraction")
println("3 - multiplication")
println("4 - division")
val choice = readLine()!!.toInt()
val result = 0
when (choice) {
    1 -> result = a + b
    2 -> result = a - b
    3 -> result = a * b
    4 -> result = a / b
}
if ((choice > 0) && (choice < 5)) {
    println("Result: $result")
} else {
    println("Invalid choice")
}
println("Thank you for using our calculator.")

Now, we'll put almost all the code into a while loop. Our condition will be that the user entered "yes", so we'll check the content of a goOn variable. This variable will be set to "yes" at the beginning since the program has to begin somehow, then we'll assign the user's input to it:

println("Welcome to our calculator")
var goOn = "yes"
while (goOn == "yes") {
    println("Enter the first number")
    val a = readLine()!!.toDouble()
    println("Enter the second number:")
    val b = readLine()!!.toDouble()
    println("Choose one of the following operations:")
    println("1 - addition")
    println("2 - subtraction")
    println("3 - multiplication")
    println("4 - division")
    val choice = readLine()!!.toInt()
    var result: Double = 0.0
    when (choice) {
        1 -> result = a + b
        2 -> result = a - b
        3 -> result = a * b
        4 -> result = a / b
    }
    if ((choice > 0) && (choice < 5)) {
        println("Result: $result")
    } else {
        println("Invalid choice")
    }
    println("Would you like to make another calculation? [yes/no]")
    goOn = readLine()!!
}
println("Thank you for using our calculator.")

The result:

Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:

Our application can now be used multiple times and is almost complete.

You've already learned quite a lot! Nothing better than a little noggin exercise, right? :) Since we've already stumbled across so-called nullable type several times (those two exclamation marks !!), we're going to talk about how it works in the next lesson, Solved tasks for Kotlin lesson 5.

In the following exercise, Solved tasks for Kotlin lesson 5, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 10x (30.7 kB)
Application includes source codes in language Kotlin

 

Previous article
Solved tasks for Kotlin lesson 4
All articles in this section
Kotlin Basic Constructs
Skip article
(not recommended)
Solved tasks for Kotlin lesson 5
Article has been written for you by Samuel Kodytek
Avatar
User rating:
1 votes
I'm intereseted in JVM languages and Swift
Activities