Welcome to the Kotlin For Loop tutorial! In this comprehensive guide, we'll dive into one of the most fundamental aspects of programming in Kotlin - the For Loop. By the end of this tutorial, you'll have a solid understanding of for loops and be ready to apply them in your projects. 📝
<a name="basics"></a>
A For Loop is a control structure that allows you to repeat a block of code a specific number of times. In Kotlin, we use for loops to iterate through collections like arrays and lists.
For loops are useful when you need to perform an action a certain number of times, like printing numbers from 1 to 10 or iterating through an array of items.
<a name="syntax"></a>
The basic syntax of a Kotlin For Loop looks like this:
for (initializer; condition; incrementor) {
// code to be executed
}Let's break down this syntax:
Here's a simple example where we print numbers from 1 to 5:
for (i in 1..5) {
println(i)
}<a name="data-structures"></a>
For loops can be used with different data structures, such as arrays and lists.
Here's an example of iterating through an array using a for loop:
val numbers = intArrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}Iterating through lists in Kotlin is quite similar to arrays:
val fruits = listOf("Apple", "Banana", "Orange", "Mango", "Pineapple")
for (fruit in fruits) {
println(fruit)
}<a name="break-continue"></a>
Sometimes, you might want to break out of a loop early or skip an iteration. Kotlin provides the break and continue keywords for this purpose.
The break keyword ends the loop immediately. Here's an example:
for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}The continue keyword skips the current iteration and moves on to the next one. Here's an example:
for (i in 1..10) {
if (i % 2 == 0) {
continue
}
println(i)
}<a name="nested"></a>
Nested for loops allow you to iterate through multiple collections at the same time. Here's an example:
val numbers1 = intArrayOf(1, 2, 3)
val numbers2 = intArrayOf(4, 5, 6)
for (number1 in numbers1) {
for (number2 in numbers2) {
println("${number1} * ${number2} = ${number1 * number2}")
}
}<a name="quiz"></a>
What is the output of the following code snippet?