Loops are essential control structures in programming that allow you to repeat a block of code multiple times until a certain condition is met. Kotlin provides two main types of loops: for
and while
. These loops enable you to iterate over collections, execute code iteratively, and automate repetitive tasks. In this guide, we’ll explore how to use for
and while
loops in Kotlin, along with examples to illustrate their usage.
The for
Loop
The for
loop in Kotlin is primarily used for iterating over collections, arrays, ranges, and other iterable objects. It allows you to perform an action on each element of the collection or iterate a specific number of times. The basic syntax of a for
loop is as follows:
for (item in collection) {
// Code to execute for each item
}
Here’s an example of a for
loop that iterates over a range of numbers and prints each value:
for (i in 1..5) {
println(i)
}
In this example, the loop iterates from 1 to 5, inclusive, and prints each value on a new line.
You can also use for
loops to iterate over collections like lists, arrays, or other iterable objects:
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println("I like $fruit")
}
This loop iterates over the fruits
list and prints a message for each fruit.
The while
Loop
The while
loop in Kotlin is used when you want to repeat a block of code as long as a given condition is true. It evaluates the condition before each iteration. The basic syntax of a while
loop is as follows:
while (condition) {
// Code to execute while the condition is true
}
Here’s an example of a while
loop that counts from 1 to 5:
var count = 1
while (count <= 5) {
println(count)
count++
}
In this example, the loop continues as long as count
is less than or equal to 5, printing the current value of count
in each iteration.
The do-while
Loop
Kotlin also provides a do-while
loop, which is similar to the while
loop but ensures that the code block is executed at least once, even if the condition is initially false
. The basic syntax of a do-while
loop is as follows:
do {
// Code to execute at least once
} while (condition)
Here’s an example of a do-while
loop that prompts the user for a positive number and repeats until a positive number is entered:
var input: Int
do {
print("Enter a positive number: ")
input = readLine()?.toIntOrNull() ?: 0
} while (input <= 0)
println("You entered a positive number: $input")
In this example, the loop continues to prompt the user until a positive number is provided.
Loop Control Statements
In Kotlin, you can control the flow of loops using specific statements:
break
: Terminates the loop prematurely, even if the condition is still true.continue
: Skips the current iteration of the loop and proceeds to the next iteration.
Here’s an example illustrating the use of break
and continue
statements:
for (i in 1..10) {
if (i % 2 == 0) {
continue // Skip even numbers
}
println(i)
if (i == 7) {
break // Terminate the loop when i is 7
}
}
In this example, continue
skips even numbers, and break
terminates the loop when i
reaches 7.
Command and Examples
Here are examples demonstrating the use of for
and while
loops in Kotlin:
Example 1: Using a for
loop to iterate over a range and calculate the sum of even numbers:
var sum = 0
for (i in 1..10) {
if (i % 2 == 0) {
sum += i
}
}
println("Sum of even numbers from 1 to 10: $sum")
Example 2: Using a while
loop to find the factorial of a number:
val number = 5
var factorial = 1
var i = 1
while (i <= number) {
factorial *= i
i++
}
println("Factorial of $number is $factorial")
These examples demonstrate how to use for
and while
loops to perform repetitive tasks, calculate values, and control program flow based on conditions.
In summary, for
and while
loops are fundamental constructs in Kotlin for controlling program flow and automating repetitive tasks. They are essential tools for iterating over collections, processing data, and solving various programming challenges. Understanding when and how to use these loops is crucial for effective Kotlin programming.