Programming in Kotlin: Fundamentals

Aug 9 2022 · Kotlin 1.6, Android 12, IntelliJ IDEA CE 2022.1.3

Part 2: Manage Control Flow

11. Understand While Loops

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Introduction Next episode: 12. Challenge: Use While Loops

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 11. Understand While Loops

You already know about using if/else statements and expressions to change the way your code behaves in certain conditions. The next big thing you will use to control your code are loops.

Imagine you’re building a chat app and you want to print out the messages between the two parties. Let’s say they’ve exchanged 100 messages between each other.

It would be inefficient to write 100 print statements.

To make repetitive operations, Kotlin provides you with loops.

A Loop, as its name suggests, is a way to repeat a code block more than once.

Such behavior is useful if you need to iterate over things multiple times, and sometimes with small changes in the behavior in between each iteration.

Loops usually have something called an exit condition. If you think about it, if you kept looping over the same piece of code, without any condition to exit the loop, you’d end up looping till infinity.

There are three loops in Kotlin: The While, Do while, and the For loops.

In this episode, you’ll cover the while and do while loops. Let’s see how to implement them! :]

To start, let’s create a while loop that will print out the numbers 1 through 9. You’ll need two things: the while loop itself, and a variable to track the number of times you’ve looped.

Start with the variable. Call it counter and set the value to 1:

var counter = 1

Now you’re ready for the loop. The while loop syntax starts with the while keyword, then a condition. A condition is simply a Boolean expression. You should recall what Boolean expressions are from the previous part of this course.

In this case, you want to print out the numbers from one to nine. So you want this loop to run up to nine, but no further. The simplest way is to say “while counter is less than ten.”

Add in following code:

while (counter < 10)

You could also say “counter is less than or equal to 9”, which means the same thing.

Next, you need to print out the value of counter each time it goes around the loop. To do that, you add a set of curly braces to hold the code to execute like so:

while (counter < 10) {

}

And then inside those curly braces, you tell Kotlin to print the current value of the counter variable:

while (counter < 10) {
    println(counter)
}

Once you’ve printed the value of counter, you need to increment the counter by one before the loop goes around again. Do you remember how to increment numbers? That’s right, using the augmented assignment operator.

Add that now:

while (counter < 10) {
  println(counter)
  counter += 1 // New code
}

Then run you your project Now when the code executes, you’ll see the numbers 1 through 9 appear in the run panel!

Each time around the loop, Kotlin prints the current value of counter, then increments counter by one. When counter is ten, the condition here is no longer true, so Kotlin stops executing the loop. This trip around each cycle of the loop is popularly known as an iteration. So you’ll hear me use that often.

To show that the condition works, go ahead and print the value of counter outside the loop like so:

... // while loop above
println(counter)

Then run your project.

And you can see that 10 is printed outside the looped values because that’s the current counter value after the condition in the loop became false. I’ll hit Cmd + / to comment out that line.

Now, what would happen if you declared counter to be ten before the loop started? That’s right, it wouldn’t run.

But what if you wanted to guarantee that a loop would execute at least once, before you check the condition for the loop? You can use a variant of the while loop called the do while loop! First, put a print statement after the while loop so you can tell in your run panel where you start counting again:

println("Counting up again")

And you also want to reset your counter to one, so do that after the “Counting up again” line:

counter = 1

Remember, you’ve declared this as a variable above, so you don’t need to redeclare counter down here you just need to reassign it to a value you want.

The syntax for a do-while loop is sort of backwards to the regular while loop. It starts with the keyword do followed by a set of curly braces with the loop code inside like so:

do {

}

Then you put the code you want to execute inside the curly braces which is to print the counter, then increment the counter by one:

do {
  println(counter)
  counter += 1
} 

Now, what condition are you going to end with? You want to count up to nine, but remember that this loop will execute first, and then the condition will be checked.

You want this to print the numbers up to and including nine, and then stop. So your condition will be counter < 10, again. Add in the condition like so:

do {
    println(counter)
    counter += 1
} while (counter < 10)

This means that when the counter is incremented to nine, the loop will run again, print nine, increment the counter to ten, and then the condition will be checked again and since it will be false this time, the loop will stop.

Run the project.

You can see in the run panel, that your new code counts up to nine again. Nice!!!

To see the difference between these two loops, see what would happen if you set the counter to 10 before the loops start. Change the counter assignments to 10.

var counter = 10

counter = 10

Then run your project.

Now you can see the difference between the two loops. With the while loop, the condition is checked, but counter is not less than ten, so the code inside its body never executes.

The do while loop, however, executes the first time and prints out “10”, and then checks the condition, finds the condition is false, and doesn’t repeat.

So the important difference is knowing when the condition is checked. A while loop checks the condition before the loop code, and do while checks the condition after.

There you go!!! Two different flavors of while loops in Kotlin!!!