Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 47 of 93.

While a for loop works great when you know the exact number of iterations, sometimes you need to keep looping until a certain condition changes. That's where the while loop comes in.

A while loop continues running as long as its condition is true:

var count = 1
while (count <= 3) {
    println(count)
    count++
}
// Output:
// 1
// 2
// 3

The loop checks the condition before each iteration. Once count becomes 4, the condition count <= 3 is false, and the loop stops.

Be careful: if the condition never becomes false, you'll create an infinite loop. Always make sure something inside the loop eventually changes the condition:

var password = ""
while (password != "secret") {
    password = readLine() ?: ""
}
println("Access granted!")

This loop keeps asking for input until the user enters "secret". The while loop is ideal when you don't know in advance how many iterations you'll need.

challenge icon

Challenge

Medium

Read an integer n from input. Use a while loop to print all numbers from n down to 1, each on a separate line.

For example, if the input is 5, the output should be:

5
4
3
2
1

Try it yourself

fun main() {
    val n = readLine()!!.toInt()
    
    // TODO: Write your code below
    // Use a while loop to print all numbers from n down to 1
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground