You are currently viewing Kotlin Looping: Everything You Need to Know

Kotlin Looping: Everything You Need to Know

Looping is a fundamental concept in programming that allows us to execute a block of code repeatedly. In Kotlin, a modern and concise programming language, you have several looping constructs at your disposal. This article explores all the looping mechanisms available in Kotlin, along with code examples and explanations. Additionally, we’ll also cover loop control statements, which provide ways to alter the flow of execution within loops.

The For Loop

The for loop in Kotlin allows you to iterate over a range, an array, or any other iterable object. It has a compact syntax that makes it easy to work with.

fun main() {

    // A list of integers
    val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    // Iterating over list elements
    for (number in numbers) {

        // Print number to the console
        println(number)

    }


}

We create a list of numbers and iterate over each element using a for loop. The loop variable number takes the value of each element in the numbers list, and we print it to the console.

Let’s see another example that iterates over a closed range of numbers 1 to 10 using the for loop:

fun main() {

    for(number in 1..10) {

        println("The current value of number is $number")

    }

}

The While Loop

The while loop is used to repeatedly execute a block of code as long as a condition remains true. It is suitable when the number of iterations is unknown.

fun main() {

    // Set counter initial value
    var count = 1

    while (count <= 10) {

        // Print the current value of counter to the console
        println("The current value of counter is $count")

        // Add 1 to counter
        count++

    }

}

We initialize the variable count to 1. The while loop continues to execute the block of code as long as the condition count <= 10 remains true. Inside the loop, we print the current value of count and then increment it by 1.

The Do-While Loop

The do-while loop is similar to the while loop, but the condition is checked at the end of the loop. This guarantees that the loop body is executed at least once.

fun main() {

    // Set counter initial value
    var count = 1

    do {

        // Print current value of counter to the console
        println("Current value of counter is $count")


        // Add 1 to counter
        count++

    } while (count <= 10)
    
}

We declare a variable count and initialize it to 1. The do-while loop executes the block of code at least once, printing the current value of count, and then increments count by 1. The loop continues as long as the condition count <= 10 is true.

Loop Control Statements

Loop control statements allow you to alter the flow of execution within loops. Kotlin provides three main loop control statements: break, continue, and return.

The break Statement

The break statement terminates the innermost loop it is located in, and the control transfers to the next statement after the loop.

fun main() {

    for (i in 1..10) {

        if (i == 6) {

            // Exit loop
            break
        }

        // Print the current value of i
        println(i)

    }
    
}

We use a for loop to iterate from 1 to 10. When the loop variable i reaches 6, the break statement is executed, and the loop terminates. As a result, the numbers 1, 2, 3, 4 and 5 are printed to the console.

The continue Statement

The continue statement skips the current iteration of a loop and moves to the next iteration.

fun main() {

    for (i in 1..10) {

        if (i == 6) {

            // Move to next iteration
            continue
        }

        // Print the current value of i
        println(i)

    }

}

When the loop variable i is equal to 6, the continue statement is executed. This skips the execution of the remaining code in that iteration and moves to the next iteration. Therefore, the number 6 is not printed, but the numbers 1, 2, 3, 4, 5, 7, 8, 9 and 10 are printed.

The return Statement

The return statement is used to terminate the execution of a loop and return from the enclosing function or block.

fun findFirstEvenNumber(numbers: List<Int>): Int {

    for (number in numbers) {

        // Check if number is divisible by 2
        if (number % 2 == 0) {

            // Return number, exit loop, and enclosing function
            return number

        }

    }

    // return -1 if no even number found
    return -1

}

fun main() {

    // List of numbers
    val numbers: List<Int> = listOf(1, 3, 7, 2, 9, 1, 4);

    // Find first even number
    val evenNumber: Int = findFirstEvenNumber(numbers)

    if(evenNumber != -1) {

        // Print even number found
        println("The first even number found in the list is $evenNumber.")

    } else {

        println("No even number found in the list of numbers provided.")

    }

}

We define a function findFirstEvenNumber that takes a list of integers as a parameter. The function uses a for loop to iterate over the numbers. When it encounters the first even number, it immediately returns that number and exits the loop and the function. If no even number is found, it returns -1.

Conclusion

The article explored the various looping mechanisms available in Kotlin. We discussed the for loop, while loop, and do-while loop, along with their respective syntax and use cases. Additionally, we covered loop control statements such as break, continue, and return, which provide ways to alter the flow of execution within loops. By mastering these looping constructs, you can efficiently iterate over collections, process data, and solve complex problems in your Kotlin programs.

Sources

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply