In Kotlin, the for
loop is a versatile control structure that allows you to iterate through ranges, arrays, collections, and other sequences of data. This guide will take you through the fundamentals of the for
loop in Kotlin, along with its usage, syntax, and examples to help you grasp this essential programming concept.
Course Outline
- Introduction to the
for
Loop- What is a
for
loop? - When to use a
for
loop in Kotlin
- What is a
- Syntax of the
for
Loop in Kotlin- Basic syntax for iterating over ranges and collections
- Using
for
Loop with Rangesfor
loop with a range of numbers- Ranges with step values
- Using
for
Loop with Arrays and Collections- Iterating through arrays and lists
- Accessing index and element pairs
- Using
for
Loop with Maps- Iterating through key-value pairs in maps
- Working with destructured entries
- Nested
for
Loops- Creating loops within loops
- Practical examples of nested
for
loops
- Advanced Techniques with
for
Loops- Using
for
loop with conditions - Combining
for
loop withbreak
andcontinue
- Using
- Examples and Exercises
1. Introduction to the for
Loop
The for
loop in Kotlin is primarily used to iterate over a sequence, which can be a range, array, list, map, or any iterable object. It’s especially useful when you know the number of iterations you need to perform.
2. Syntax of the for
Loop in Kotlin
The basic syntax of a for
loop in Kotlin is:
for (item in sequence) {
// Code to execute for each item
}
Here, item
represents the element in each iteration, and sequence
is the collection or range to loop over.
3. Using for
Loop with Ranges
Iterating Over a Range of Numbers
A range is defined by two values, separated by two dots (..
). Here’s how you can use a for
loop to iterate through a range:
for (i in 1..5) {
println(i)
}
Output:
Copy code1
2
3
4
5
Using Step Values
You can specify a step value to control the increment in each iteration.
for (i in 1..10 step 2) {
println(i)
}
Output:
Copy code1
3
5
7
9
Descending Order with downTo
To loop in reverse, use downTo
:
for (i in 5 downTo 1) {
println(i)
}
Output:
Copy code5
4
3
2
1
4. Using for
Loop with Arrays and Collections
Iterating Through Arrays
Use a for
loop to iterate over each element in an array:
val fruits = arrayOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
Output:
Copy codeApple
Banana
Cherry
Using Indices
To get the index of each element, use .indices
:
for (index in fruits.indices) {
println("Index $index: ${fruits[index]}")
}
Output:
yamlCopy codeIndex 0: Apple
Index 1: Banana
Index 2: Cherry
Accessing Index and Element Pairs
You can also access both index and element with the withIndex()
function:
for ((index, fruit) in fruits.withIndex()) {
println("Index $index: $fruit")
}
Output:
yamlCopy codeIndex 0: Apple
Index 1: Banana
Index 2: Cherry
5. Using for
Loop with Maps
Maps store data as key-value pairs. To iterate through them, you can use the following syntax:
val ageMap = mapOf("Alice" to 23, "Bob" to 29, "Catherine" to 31)
for ((name, age) in ageMap) {
println("$name is $age years old")
}
Output:
csharpCopy codeAlice is 23 years old
Bob is 29 years old
Catherine is 31 years old
6. Nested for
Loops
A nested for
loop is when you have one for
loop inside another. This is useful for iterating through multidimensional arrays or creating patterns.
for (i in 1..3) {
for (j in 1..3) {
println("i: $i, j: $j")
}
}
Output:
yamlCopy codei: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
...
7. Advanced Techniques with for
Loops
Using Conditions in for
Loops
You can add if
conditions inside a for
loop to filter elements.
for (i in 1..10) {
if (i % 2 == 0) {
println(i)
}
}
Output:
Copy code2
4
6
8
10
Using break
and continue
break
: Stops the loop entirely.continue
: Skips to the next iteration of the loop.
for (i in 1..10) {
if (i == 5) break
println(i)
}
Output:
Copy code1
2
3
4
for (i in 1..10) {
if (i % 2 == 0) continue
println(i)
}
Output:
Copy code1
3
5
7
9
8. Examples and Exercises
Example 1: Print Multiplication Table
Create a for
loop that prints a multiplication table for a number:
val number = 5
for (i in 1..10) {
println("$number * $i = ${number * i}")
}
Example 2: Count Elements in a List
Count the number of even numbers in a list.
val numbers = listOf(1, 2, 3, 4, 5, 6)
var evenCount = 0
for (number in numbers) {
if (number % 2 == 0) evenCount++
}
println("There are $evenCount even numbers.")
Exercise 3: Display Names with a Prefix
Given a list of names, print each name with a “Hello” prefix.
val names = listOf("John", "Emma", "Chris")
for (name in names) {
println("Hello, $name!")
}
Conclusion
The for
loop is a fundamental construct in Kotlin, enabling you to iterate over collections, arrays, and ranges with ease. It’s flexible, allowing for nested loops, conditions, and control flow statements like break
and continue
. By mastering for
loops, you’ll be equipped to handle various data structures and algorithms, making your code more efficient and organized.