5. Bucles: Repetición inteligente
for con rangos
Kotlin tiene rangos poderosos que hacen los bucles limpios y expresivos:
rangos.kt
KOTLIN
1 // Rango inclusivo: 1, 2, 3, 4, 5
2 for (i in 1..5) {
3 println(i)
4 }
5
6 // Rango excluyente: 1, 2, 3, 4 (sin el 5)
7 for (i in 1 until 5) {
8 print("$i ") // 1 2 3 4
9 }
10
11 // Decremento
12 for (i in 5 downTo 1) {
13 print("$i ") // 5 4 3 2 1
14 }
15
16 // Con step (saltos)
17 for (i in 0..10 step 2) {
18 print("$i ") // 0 2 4 6 8 10
19 }
while y do-while
Funcionan igual que en otros lenguajes:
while.kt
KOTLIN
1 var contador = 5
2 while (contador > 0) {
3 print("$contador ")
4 contador--
5 }
6 // 5 4 3 2 1
7
8 do {
9 println("Se ejecuta al menos una vez")
10 } while (false)
repeat: Repetir N veces
Una alternativa elegante para bucles con contador fijo:
repeat.kt
KOTLIN
1 repeat(5) {
2 println("Iteración $it")
3 }
4
5 // Con índice
6 repeat(3) { i ->
7 println("Posición: $i")
8 }
break y continue
Controla el flujo de tus bucles:
break-continue.kt
KOTLIN
1 // break: salir del bucle
2 for (i in 1..10) {
3 if (i == 5) break
4 print("$i ") // 1 2 3 4
5 }
6
7 // continue: saltar a la siguiente iteración
8 for (i in 1..5) {
9 if (i == 3) continue
10 print("$i ") // 1 2 4 5
11 }
💻 Misión
Imprime la tabla de multiplicar del 7 usando un bucle for con rangos. Luego usa repeat para imprimir "Kotlin" 3 veces.
👁️ Ver solución sugerida
main.kt
KOTLIN
1 fun main() {
2 // Tabla del 7
3 for (i in 1..10) {
4 println("7 x $i = ${7 * i}")
5 }
6
7 // Repeat
8 repeat(3) {
9 println("Kotlin")
10 }
11 }