In Kotlin, for loops are a powerful way to iterate over a range of numbers. This type of loop is essential for scenarios where you need to execute a block of code a specific number of times. In this article, we'll explore how to use for loops with ranges in Kotlin, and look at some practical examples.
Using Ranges in Kotlin
A range in Kotlin is defined using the .. operator. For instance, a range from 1 to 5 is written as 1..5. Kotlin also offers a rangeTo() function that provides the same functionality. Here's how you define a range:
val range = 1..5
Basic for Loop with Ranges
The basic syntax for a for loop using ranges in Kotlin is straightforward:
for (i in 1..5) {
println(i)
}
This loop will print numbers from 1 to 5 to the console. The variable i iterates over each number in the range.
Using downTo for Reverse Order
If you need to iterate over a range in reverse order, you can use the downTo keyword:
for (i in 5 downTo 1) {
println(i)
}
This will print numbers in descending order from 5 to 1.
Specifying Steps in a for Loop
You may also specify step values to skip numbers within the range. This is done using the step keyword:
for (i in 1..10 step 2) {
println(i)
}
In this loop, starting from 1, every second number will be printed, resulting in the output of 1, 3, 5, 7, 9.
Example: Summing Numbers in a Range
Here's a full example where we use a for loop with a range to calculate the sum of numbers from 1 to 100:
var sum = 0
for (i in 1..100) {
sum += i
}
println("Sum: $sum")
This will calculate and print the sum of numbers from 1 to 100, which is 5050.
Conclusion
Using for loops with ranges in Kotlin provides a convenient way to work with sequences of numbers. Whether iterating in ascending, descending order, or with a specific step, Kotlin's range capabilities make loop handling intuitive and efficient. By understanding these basics, you can effectively harness the power of iteration in your Kotlin programs.