Kotlin Loops
Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. In Kotlin, loops help you automate repetitive tasks, iterate through collections, and implement algorithms efficiently. This guide covers all the loop types in Kotlin with examples to help you understand when and how to use each one.
Introduction to Loops
In programming, loops enable you to repeat a block of code multiple times rather than writing the same code over and over. This makes your code more concise, readable, and maintainable. Kotlin provides several types of loops:
for
loopswhile
loopsdo-while
loops
Let's explore each type in detail.
For Loops
The for
loop in Kotlin is primarily designed for iterating over ranges, arrays, collections, or anything that provides an iterator. It's more concise and safer than traditional C-style for loops.
Basic For Loop with Ranges
In Kotlin, ranges are a powerful feature often used with for loops.
fun main() {
// Loop through numbers 1 to 5
for (i in 1..5) {
println("Number: $i")
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Iterating in Reverse Order
To iterate in reverse order, use the downTo
keyword:
fun main() {
// Loop from 5 down to 1
for (i in 5 downTo 1) {
println("Counting down: $i")
}
}
Output:
Counting down: 5
Counting down: 4
Counting down: 3
Counting down: 2
Counting down: 1
Specifying Step Size
You can control the step size using the step
keyword:
fun main() {
// Count from 1 to 10, but increment by 2 each time
for (i in 1..10 step 2) {
println("Odd number: $i")
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Iterating Through Collections
The for
loop is great for iterating through collections like arrays, lists, and maps:
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry", "Date")
for (fruit in fruits) {
println("I like $fruit")
}
// With index
for ((index, fruit) in fruits.withIndex()) {
println("Fruit at position $index is $fruit")
}
}
Output:
I like Apple
I like Banana
I like Cherry
I like Date
Fruit at position 0 is Apple
Fruit at position 1 is Banana
Fruit at position 2 is Cherry
Fruit at position 3 is Date
Iterating Through Maps
For hashmaps or dictionaries, you can iterate through key-value pairs:
fun main() {
val fruitInventory = mapOf(
"Apple" to 10,
"Banana" to 5,
"Cherry" to 7
)
for ((fruit, quantity) in fruitInventory) {
println("We have $quantity ${fruit}s in stock")
}
}
Output:
We have 10 Apples in stock
We have 5 Bananas in stock
We have 7 Cherrys in stock
While Loops
A while
loop executes a block of code repeatedly as long as a specified condition is true
.
Basic While Loop
Here's the basic structure of a while loop:
fun main() {
var count = 1
while (count <= 5) {
println("Count: $count")
count++
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Using While for User Input Validation
While loops are often used for validating user input:
fun main() {
var userInput: String?
var validInput = false
println("This is a simulation of validating user input")
println("(In a real program, you'd use readLine() to get input)")
// Simulating a sequence of inputs
val inputs = listOf("invalid", "still wrong", "correct password")
var inputIndex = 0
while (!validInput && inputIndex < inputs.size) {
// Simulate getting the next input
userInput = inputs[inputIndex++]
println("User entered: $userInput")
if (userInput == "correct password") {
validInput = true
println("Access granted!")
} else {
println("Invalid input. Please try again.")
}
}
}
Output:
This is a simulation of validating user input
(In a real program, you'd use readLine() to get input)
User entered: invalid
Invalid input. Please try again.
User entered: still wrong
Invalid input. Please try again.
User entered: correct password
Access granted!
Do-While Loops
A do-while
loop is similar to a while loop, but it guarantees that the code block executes at least once before checking the condition.
Basic Do-While Loop
fun main() {
var count = 1
do {
println("Count: $count")
count++
} while (count <= 5)
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Do-While for Menu Systems
Do-while loops are ideal for menu-driven programs:
fun main() {
var choice: Int
// Simulating a menu system
do {
println("\n---- Menu ----")
println("1. Option One")
println("2. Option Two")
println("3. Option Three")
println("0. Exit")
// In a real program, you would get user input
// For this example, we'll simulate a sequence of choices
val choices = listOf(1, 2, 3, 0)
choice = choices[Math.floor(Math.random() * choices.size).toInt()]
println("Selected: $choice")
when (choice) {
1 -> println("Processing Option One...")
2 -> println("Processing Option Two...")
3 -> println("Processing Option Three...")
0 -> println("Exiting program...")
else -> println("Invalid choice!")
}
} while (choice != 0)
}
Note: The output will vary based on the random selections, but the loop will continue until option 0 is selected.
Loop Control Statements
Kotlin provides statements to control the flow within loops:
Break Statement
The break
statement terminates the loop immediately:
fun main() {
for (i in 1..10) {
if (i == 5) {
println("Breaking at $i")
break
}
println("Number: $i")
}
println("Loop ended")
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Breaking at 5
Loop ended
Continue Statement
The continue
statement skips the current iteration and proceeds to the next one:
fun main() {
for (i in 1..5) {
if (i == 3) {
println("Skipping number 3")
continue
}
println("Number: $i")
}
}
Output:
Number: 1
Number: 2
Skipping number 3
Number: 4
Number: 5
Labeled Breaks and Continues
Kotlin supports labels that allow you to break or continue from specific loops in nested loop structures:
fun main() {
outerLoop@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) {
println("Breaking outer loop when i=$i and j=$j")
break@outerLoop
}
println("i=$i, j=$j")
}
}
}
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Breaking outer loop when i=2 and j=2
Real-World Examples
Example 1: Processing Data in Batches
Here's an example of how loops can be used to process data in batches:
fun main() {
val data = listOf("Item1", "Item2", "Item3", "Item4", "Item5",
"Item6", "Item7", "Item8", "Item9", "Item10")
val batchSize = 3
var batchNumber = 1
for (i in data.indices step batchSize) {
println("\nProcessing Batch #$batchNumber")
// Calculate the end index for the current batch
val endIndex = minOf(i + batchSize - 1, data.lastIndex)
// Process items in the current batch
for (j in i..endIndex) {
println("Processing ${data[j]}")
}
batchNumber++
}
}
Output:
Processing Batch #1
Processing Item1
Processing Item2
Processing Item3
Processing Batch #2
Processing Item4
Processing Item5
Processing Item6
Processing Batch #3
Processing Item7
Processing Item8
Processing Item9
Processing Batch #4
Processing Item10
Example 2: Building a Simple Progress Bar
This example shows how to create a simple text-based progress bar:
fun main() {
val totalSteps = 10
val progressBarLength = 20
println("Downloading file...")
for (step in 1..totalSteps) {
// Calculate progress percentage
val progressPercentage = step * 100 / totalSteps
// Calculate how many characters should be filled
val filledLength = progressBarLength * step / totalSteps
// Create the progress bar string
val bar = "[" + "=".repeat(filledLength) + " ".repeat(progressBarLength - filledLength) + "]"
// Print the progress bar
println("$bar $progressPercentage%")
// In a real application, you'd do some work here
Thread.sleep(200) // Simulate work being done
}
println("Download complete!")
}
Output:
Downloading file...
[== ] 10%
[==== ] 20%
[====== ] 30%
[======== ] 40%
[========== ] 50%
[============ ] 60%
[============== ] 70%
[================ ] 80%
[================== ] 90%
[====================] 100%
Download complete!
Summary
In this guide, we've explored Kotlin's loop constructs:
- For loops: Perfect for iterating over ranges and collections
- While loops: Continue executing as long as a condition is true
- Do-While loops: Similar to while loops but execute at least once
- Loop control statements: Break, continue, and labeled breaks/continues
Loops are essential in programming as they help you automate repetitive tasks and process data efficiently. Choose the right loop based on your specific requirements:
- Use
for
loops when you know the number of iterations in advance - Use
while
loops when you need to continue until a condition is met - Use
do-while
loops when you need to execute the code at least once
Practice Exercises
To strengthen your understanding of Kotlin loops, try these exercises:
- Write a program to print all even numbers between 1 and 20 using a for loop.
- Create a program that calculates factorial of a number using a while loop.
- Write a program that prints the Fibonacci sequence up to a specified number.
- Create a nested loop to print a multiplication table from 1 to 10.
- Write a program that simulates a simple guessing game using do-while.
Additional Resources
- Kotlin Official Documentation on Control Flow
- Kotlin Playground - Practice loops in your browser
- Effective Java in Kotlin - Advanced programming techniques
By mastering loops in Kotlin, you'll be equipped to tackle a wide range of programming challenges more efficiently.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)