Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Loops: for and while | Functions and Control Flow
/
Introduction to Kotlin

bookLoops: for and while

Desliza para mostrar el menú

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

Main.kt

copy
123456789101112131415
package 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.

question mark

Which statement about loops in Kotlin is correct?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 3. Capítulo 3
some-alt