Programming in Kotlin: Fundamentals

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

Part 2: Manage Control Flow

15. Learn more Loop Features

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: 14. Challenge: Use For Loops Next episode: 16. Simplify Code with When Expressions

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: 15. Learn more Loop Features

So far you’ve used loops to iterate over ranges.

But sometimes you need to stop iterating based on some conditions. Or you need to skip certain elements from processing. This is called exiting early, and there are two ways to achieve such behavior.

Using continue and break statements. With continue, you can stop the current iteration of a loop, and move onto the next one. Using break, you can break out of a loop entirely, and stop all the future iterations. You’ll see how to do so in a minute.

Nested loops are just loops within loops, when you need two layers or levels of processing.

If you’re working with nested loops, when exiting from the loop early you need to specify which of the nested loops you want to exit from. This can be achieved by using labels. Labels are like checkpoints in code, which you can travel back to when needed.

You’ll learn all about these in this episode too.

There’s a ton of new concepts to cover here, so without further ado, let’s get started! :]

Let’s start off by learning about exiting early from loops. Create a for loop to iterate over numbers from 0 to 14:

for (num in 0..14) {
  println(num)
}

Now, let’s say you want to print only the odd numbers within this range.

Let’s tweak the for loop to reflect this:

for (num in 0..14) {
  if (num%2 == 0) {
    continue
  }
  
  println(num)
}

Here you’re checking if the number is an even number by using the modulo operator in Kotlin. The modulo operator returns the remainder of an operation. When the number modulo 2 equals 0, then the number is even.

If it is an even number you skip the current iteration of the loop and proceed to the next iteration. You do this using the continue statement. And this process keeps checking for even numbers until the loop ends.

Run the project to check the output.

You can see only the odd numbers within that range are printed.

Now, lets say these number range are for a 14 day project. With this, it means you work every other day with a day off in between.

Let’s say at some point you want to stop execution of the loop maybe because there’s a new boss that wants the workers to work less. In our case let’s say you want the workiers to stop work after the seventh day. You can incorporate this to your for loop with the following code:

for (num in 0..14) {
  if (num%2 == 0) {
    continue
  }

  println(num)

  if (num == 7) {
    println("Get some rest")
    break
  }
}

You can see the break statement is used after the print statement. So after the text is printed out, the loop stops and exits.

Run the project once more to see that you get to stop work after the 7th day!

So far, you’ve created loops that only goes in one dimension. You been looping things in linear space.

Loops can also be used to traverse or represent two dimensional data structure, like a Matrix, or three dimensional structure, like a Cube.

Two dimensional arrays or collections, also called Matrices, are used quite often. For example in images, which have a matrix of pixels, and image processing. Or in any kind of application which uses a calendar, where each calendar day can have multiple items that have happened on that day.

I know, math stuffs can be boring. Plus, we dont cover collections in this course. You’ll learn about that in the next course. So lets just use what you’ve learned so far to demonstrate a two dimensional structure.

You’ll use a nested loop to represent a two dimensional structure. Enter the following code:

for (row in 0..5) {
  for (column in 0..5) {
    print("x\t")
  }
  println()
}

In this loop, you’re printing out xs. Do note the use of \t in the string. This is used to add tab spaces between each item in the column. In the end you’ll get a visual representation of a 6 by 6 (6x6) matrix.

Run the project and you should see a 6x6 matrix of xs. .

But how do you exit the parent loop from the nested loop? Or how do you break only the nested loop if you need to stop an entire row from being processed?

You can do so by using labels.

To add a label to a for loop, do the following:

row@ for (row in 0..5) {
...
}

You’ve now labeled the outer loop. A label is like a checkpoint mark. You can use it to go back or refer to a location in code. If you ever want to stop the nested loops, you can break the row label, and that’s it.

Now add the label for the inner loop which represents the column like so:

row@ for (row in 0..5) {
  column@ for (column in 0..5) {
    print("x\t")
  }
  println()
}

To spice things up a bit, let’s remove a section of a row based on a condition. To do this, you can add the following code:

row@ for (row in 0..5) {
  column@ for (column in 0..5) {
    if (column == 2 && row == 2) {
      break@column
    }
    print("x\t")
  }
  println()
}

Using the label again, you’ve done the following:

  • when the nested loop is started, and you’ve reached the third column and the third row, you’ll break the nested loop, and
  • continue on to the next row.

This will leave an incomplete matrix.

Run the project and you should see one row with only two xs.

Another thing you could do, is break the row, and stop the rest of the matrix from printing out. To do this, break the row instead of the column like so:

row@ for (row in 0..5) {
  column@ for (column in 0..5) {
    if (column == 2 && row == 2) {
      break@row
    }
    print("x\t")
  }
  println()
}

This will print out the first two rows, then print two elements of the third row, and stop printing out elements from the rest of the matrix.

Run the project and you should see one row with only two xs.

Awesome!!! You’re now a pro at working with loops.