Start learning free

LESSON 152 OF 348 · LOOPING OVER ARRAY INDICES

Continue in For Loops in Kotlin

Lesson Read the full explanation

With the continue statement we can stop the current iteration of the loop, and continue with the next.

When Kotlin hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

val ages = intArrayOf(10, 30, 21, 19, 25)

for (age in ages) {
	if (age < 21) {
		continue
	}
	println("Someone of age $age entered the bar.")
}

The output of this program is:

Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
	
2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. println
	
3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. println

4. Forth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
      
5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. println

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · LOOPING OVER ARRAY INDICES

    Continue In For Loops in Kotlin, explained

    What continue does

    The continue statement ends the current iteration of a loop and jumps straight to the next one. Any code below it in the loop body is skipped for that element, but the loop itself keeps going. Compare break, which ends the whole loop.

    The example below lets in only people aged 21 or more:

    val ages = intArrayOf(10, 30, 21, 19, 25)
    
    for (age in ages) {
        if (age < 21) {
            continue
        }
        println("Someone of age $age entered the bar.")
    }
    
    Someone of age 30 entered the bar.
    Someone of age 21 entered the bar.
    Someone of age 25 entered the bar.
    

    The ages 10 and 19 print nothing. The iterations go like this:

    1. age = 10: the test age < 21 is true, so continue runs and the println is skipped.
    2. age = 30: the test is false, so the program reaches the println.
    3. age = 21: 21 is not less than 21, so the test is false and the line prints. The boundary value is let in.
    4. age = 19: skipped, like the first.
    5. age = 25: printed.

    The string "... $age ..." is a string template: Kotlin replaces $age with the variable's value.

    The exercise

    The task is to let into the arena only the people whose height is at least 170. The starting code is the array:

    val heights = intArrayOf(180, 139, 174, 190, 162)
    

    The steps:

    1. Loop over the heights. for (height in heights) gives each value in turn. Kotlin works out the type of height from the array, so you don't write one.
    2. Skip the short ones. Inside the loop, if height is less than 170, call continue. The test checks the rejection condition ("less than 170"), which is the opposite of the requirement ("at least 170").
    3. Print the rest. Below the if, print height. This line is reached only by heights that passed the check.
    val heights = intArrayOf(180, 139, 174, 190, 162)
    
    for (height in heights) {
        if (height < 170) {
            continue
        }
        println(height)
    }
    

    The output is:

    180
    174
    190
    

    139 and 162 are skipped. A height of exactly 170 would be printed, because 170 is not less than 170.

    Continue or a positive if?

    The same result is possible without continue, by testing the condition you want and putting the work inside the if:

    for (height in heights) {
        if (height >= 170) {
            println(height)
        }
    }
    

    Both versions print the same three numbers. With one statement to run, the second is shorter. continue pays off when the loop body is long: rejecting the unwanted elements at the top keeps the real work at one level of indentation instead of burying it inside a large if block.

    Continue in nested loops

    A plain continue applies to the innermost loop it is in. To move on to the next iteration of an outer loop, put a label on that loop:

    val g = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6))
    outer@ for (row in g) {
        for (v in row) {
            if (v % 2 == 0) continue@outer
            println(v)
        }
    }
    

    For the first row, 1 prints, then 2 triggers continue@outer, which abandons that row. For the second row, 4 is even, so the row is abandoned before anything prints. The output is just 1.

    Common mistakes

    • Putting the work before the check. If println(height) comes above the if, every height is printed, because the skip happens too late to matter.
    • Using the wrong comparison. height <= 170 would wrongly skip a person who is exactly 170. The requirement "at least 170" means only values below 170 are skipped.
    • Using break by mistake. break would stop at 139 and print only 180. Use continue when later elements still need to be processed.
    • Continue in a while loop. Be careful when the counter is updated at the bottom of the body: continue skips that update too, and the loop can run forever. A for loop advances on its own, which avoids this problem.

    Key takeaways

    • continue skips the rest of the current iteration and moves to the next element.
    • It is written as a guard at the top of the loop body: test for what to skip, then do the work.
    • With nested loops, plain continue affects the innermost loop; continue@label targets an outer one.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free