Menu
Coddy logo textTech

Do-While Loop

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

The do-while loop is similar to the while loop, but with one key difference: it always executes the code block at least once before checking the condition.

Here's the structure:

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

The code inside the do block runs first, then the condition is checked. If the condition is true, the loop repeats. This is useful when you need the code to run at least once regardless of the condition.

Consider this example where the condition is false from the start:

var x = 10
do {
    println("This prints once!")
} while (x < 5)
// Output: This prints once!

Even though x < 5 is false, the message still prints because the condition is checked after the first execution. With a regular while loop, nothing would print at all.

challenge icon

Challenge

Medium

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

The loop should execute at least once, even if n is less than 1. In that case, it should still print 1.

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

1
2
3
4

If the input is 0, the output should be:

1

Try it yourself

fun main() {
    val n = readLine()!!.toInt()
    
    // TODO: Write your code below
    // Use a do-while loop to print numbers from 1 to n
    // Remember: the loop should execute at least once
    
}
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