Kotlin For Loop
Loops are fundamental programming constructs that allow us to execute a block of code repeatedly. In Kotlin, the for
loop provides a clean and concise way to iterate over collections, ranges, and other iterables. Unlike other languages like Java or C++, Kotlin's for
loop is designed to be more readable and less error-prone.
Basic Syntax of For Loop
In Kotlin, the basic syntax of a for
loop is:
for (item in collection) {
// code to be executed for each item
}
Where:
item
is a variable that will hold the current element from the collection during each iterationcollection
is any object that provides an iterator (arrays, lists, ranges, etc.)
Iterating Over Ranges
One of the most common uses of for
loops is to iterate over a range of numbers. In Kotlin, you can create a range using the ..
operator.
Example: Iterating Through a Number Range
fun main() {
// Printing numbers from 1 to 5
for (number in 1..5) {
println("Number: $number")
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Iterating in Reverse
To iterate in reverse order, you can use the downTo
function:
fun main() {
// Printing numbers from 5 down to 1
for (number in 5 downTo 1) {
println("Number: $number")
}
}
Output:
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1
Specifying a Step
You can specify the step (increment or decrement) using the step
function:
fun main() {
// Printing even numbers from 2 to 10
for (number in 2..10 step 2) {
println("Even number: $number")
}
// Printing every third number counting down from 10 to 1
for (number in 10 downTo 1 step 3) {
println("Countdown: $number")
}
}
Output:
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
Countdown: 10
Countdown: 7
Countdown: 4
Countdown: 1
Iterating Over Collections
Kotlin's for
loop makes it easy to iterate over any collection like arrays, lists, sets, and maps.
Example: Iterating Through an Array
fun main() {
val fruits = arrayOf("Apple", "Banana", "Cherry", "Date", "Elderberry")
for (fruit in fruits) {
println("I like $fruit")
}
}
Output:
I like Apple
I like Banana
I like Cherry
I like Date
I like Elderberry
Example: Iterating Through a List
fun main() {
val vegetables = listOf("Carrot", "Broccoli", "Spinach", "Tomato")
for (vegetable in vegetables) {
println("$vegetable is healthy")
}
}
Output:
Carrot is healthy
Broccoli is healthy
Spinach is healthy
Tomato is healthy
Accessing Indices During Iteration
Sometimes you need to access both the index and the value during iteration. Kotlin provides the withIndex()
function for this purpose:
fun main() {
val colors = listOf("Red", "Green", "Blue", "Yellow")
for ((index, color) in colors.withIndex()) {
println("Color at position $index is $color")
}
}
Output:
Color at position 0 is Red
Color at position 1 is Green
Color at position 2 is Blue
Color at position 3 is Yellow
Iterating Over Characters in a String
You can iterate through each character in a string using a for
loop:
fun main() {
val greeting = "Hello"
for (char in greeting) {
println("Character: $char")
}
}
Output:
Character: H
Character: e
Character: l
Character: l
Character: o
Iterating Over Maps
When iterating over maps, you can access both the key and value:
fun main() {
val capitalCities = mapOf(
"USA" to "Washington D.C.",
"UK" to "London",
"India" to "New Delhi",
"Australia" to "Canberra"
)
for ((country, capital) in capitalCities) {
println("The capital of $country is $capital")
}
}
Output:
The capital of USA is Washington D.C.
The capital of UK is London
The capital of India is New Delhi
The capital of Australia is Canberra
Using the until
Function
If you want to exclude the upper bound in a range, you can use the until
function:
fun main() {
// Prints numbers from 1 to 4 (excludes 5)
for (number in 1 until 5) {
println("Number: $number")
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Practical Example: Calculating Factorial
Here's a real-world example of using a for
loop to calculate the factorial of a number:
fun main() {
val number = 5
var factorial = 1
for (i in 1..number) {
factorial *= i
}
println("Factorial of $number is $factorial")
}
Output:
Factorial of 5 is 120
Nested For Loops
You can nest for
loops to work with multi-dimensional data structures:
fun main() {
// Creating a multiplication table
for (i in 1..5) {
for (j in 1..5) {
print("${i * j}\t")
}
println() // Move to the next line after each row
}
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Breaking and Continuing in For Loops
Using break
The break
statement lets you exit a loop early:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println("Numbers until we find 6:")
for (number in numbers) {
if (number == 6) {
break // Exit the loop when we find 6
}
println(number)
}
}
Output:
Numbers until we find 6:
1
2
3
4
5
Using continue
The continue
statement skips the current iteration and proceeds to the next one:
fun main() {
println("Odd numbers between 1 and 10:")
for (number in 1..10) {
if (number % 2 == 0) {
continue // Skip even numbers
}
println(number)
}
}
Output:
Odd numbers between 1 and 10:
1
3
5
7
9
Labeling For Loops
When working with nested loops, you can use labels to break or continue from a specific loop:
fun main() {
outerLoop@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) {
break@outerLoop // Breaks the outer loop
}
println("i = $i, j = $j")
}
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Summary
Kotlin's for
loop is a powerful and flexible tool for iterating over various types of data structures:
- Use
for
loops to iterate over ranges, collections, strings, and maps - Range operators:
..
(inclusive),until
(exclusive),downTo
, andstep
- Access indices with
withIndex()
- Control loop execution with
break
andcontinue
- Label loops when working with nested structures
The for
loop is just one of several control flow structures in Kotlin. When combined with other control flow statements like if
, when
, and while
, you can create sophisticated and efficient programs.
Exercises
To practice using Kotlin's for
loops, try these exercises:
- Write a program that prints all the prime numbers between 1 and 50.
- Create a triangle pattern using nested
for
loops:*
**
***
****
***** - Write a program that iterates through a list of strings and counts how many start with the letter 'A'.
- Implement FizzBuzz (print "Fizz" for numbers divisible by 3, "Buzz" for numbers divisible by 5, and "FizzBuzz" for numbers divisible by both).
- Create a program that finds all pairs of numbers in an array that sum to a specified value.
Additional Resources
- Kotlin Documentation on Control Flow
- Kotlin Playground - Try out for loops interactively
- Iterators in Kotlin - Learn more about how iteration works behind the scenes
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)