Loops: for and while
Swipe um das Menü anzuzeigen
Loops allow you to repeat a block of code multiple times, making your programs more efficient and flexible. In Kotlin, the two most common types of loops are the for loop and the while loop. You use a for loop when you know ahead of time how many times you want to repeat an action, such as iterating over a range of numbers or a collection. The while loop is useful when you want to repeat an action until a certain condition is no longer true.
The basic syntax for a for loop in Kotlin looks like this:
for (item in collection) {
// code to repeat
}
You can also use a range, such as 1..5, to repeat an action a specific number of times.
A while loop in Kotlin has this syntax:
while (condition) {
// code to repeat
}
The code inside the loop runs as long as the condition is true. When the condition becomes false, the loop stops.
Main.kt
123456789101112131415package com.example fun main() { // Using a for loop to print numbers 1 to 5 for (number in 1..5) { println("For loop iteration: $number") } // Using a while loop to print numbers 1 to 5 var count = 1 while (count <= 5) { println("While loop iteration: $count") count++ } }
In this code, the for loop iterates over the range 1..5, printing each number. The loop variable number takes each value from 1 to 5 in turn, and the code inside the loop runs once for each value. The while loop achieves the same result, but it uses a variable called count that starts at 1. The loop continues as long as count is less than or equal to 5. Inside the loop, the program prints the current value of count and then increases it by 1. Both loops produce the same output, but they use different approaches. Use a for loop when you know exactly how many times you want to repeat an action, and a while loop when you want to repeat until a condition changes.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen