Start learning free

LESSON 115 OF 348 · WHILE LOOPS & FOR LOOPS

The While Loop in Kotlin: Syntax, Counter and Condition

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while(condition) {
	instruction1
	instruction2
	...
}

Let's check an example:

var count = 1
while (count <= 5) {
	println("I made a mistake")
	count++
}
println("Finished!")

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes. 
	b. println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 2
	
2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes. 
	b. println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 3
	
3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes. 
	b. println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 4
	
4. Forth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes. 
	b. println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes. 
	b. println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 6
	
6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No. 
	b. Terminate the loop.

	
7. println("Finished!") => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · WHILE LOOPS & FOR LOOPS

    The While Loop in Kotlin, explained

    What a while loop does

    A while loop repeats a block of instructions for as long as a condition is true. Its shape is:

    while (condition) {
        instruction1
        instruction2
        // ...
    }
    

    Before every pass, Kotlin evaluates condition, which must be a Boolean. If it is true, the body runs once and Kotlin evaluates the condition again. If it is false, the loop ends and the program continues with the line after the closing brace. You can think of a while loop as an if statement that jumps back and checks again after every run.

    An example

    var count = 1
    while (count <= 5) {
        println("I made a mistake")
        count++
    }
    println("Finished!")
    

    The output is the message five times, followed by Finished!. Here is the loop traced step by step:

    CheckcountConditionResult
    111 <= 5, trueprints, count becomes 2
    222 <= 5, trueprints, count becomes 3
    333 <= 5, trueprints, count becomes 4
    444 <= 5, trueprints, count becomes 5
    555 <= 5, trueprints, count becomes 6
    666 <= 5, falsethe loop ends

    The condition is checked six times and the body runs five times. The check that fails is what ends the loop. After that, println("Finished!") runs once.

    The three parts of a counting loop

    The update matters as much as the condition. A loop only ends if something inside it eventually makes the condition false, and for a counting loop that something is the counter.

    Almost every counting while loop has the same three parts:

    1. Initialization. A variable that starts at a chosen value, written before the loop: var count = 1.
    2. Condition. A test, in the parentheses, that says whether to go on: count <= 5.
    3. Update. A change to the variable inside the body: count++. Without it, the condition never changes.

    Choosing the condition

    The same pattern fits many tasks. Change the starting value, the condition or the update, and the loop does something different. To count from 1 to 5 you start at 1 and test <= 5. To count down you start high, test >= and subtract. When you design a loop, ask three questions: where does the variable start, when should the loop stop, and how does each pass move the variable toward that stop?

    The exercise

    The task is to print "I promise to learn coding." five times with a loop. The lesson builds it in four steps.

    1. Declare the counter. Write var counter = 1. It must be var, not val, because the loop will change it. Reassigning a val is a compile error.
    2. Write the loop with its condition. while (counter <= 5) lets the body run for the values 1, 2, 3, 4 and 5, which is five times.
    3. Print inside the body. println("I promise to learn coding.") runs on each pass.
    4. Update the counter. counter++ adds 1 to the counter at the end of each pass. This is what eventually makes the condition false.
    var counter = 1
    while (counter <= 5) {
        println("I promise to learn coding.")
        counter++
    }
    

    Gotchas

    • Forgetting the update. If counter++ is missing, counter stays 1, the condition 1 <= 5 is always true and the loop never ends. The program prints the message forever. This is an infinite loop.
    • Using val for the counter. The compiler rejects counter++ on a val with the error 'val' cannot be reassigned.
    • Off-by-one errors. Starting at 1 with <= 5 gives five passes. Starting at 0 with < 5 also gives five. Mixing the two, such as starting at 1 with < 5, gives four.
    • A condition that is false at the start. The condition is checked before the first pass, so a while loop can run zero times. With var k = 5 and while (k < 5), the body never runs.
    • The condition must be a Boolean. Kotlin doesn't treat numbers as true or false, so while (counter) with an Int doesn't compile. Write a comparison such as counter <= 5.
    • The counter outlives the loop. It is declared before the loop, so it can be read after it. When the example above ends, count is 6, the first value that made the condition false.

    Key takeaways

    • while (condition) { ... } repeats its body as long as the condition is true.
    • The condition is checked before every pass, including the first.
    • A counting loop needs a starting value, a condition and an update.
    • Declare the counter with var, and always make sure the body moves it toward the end of the loop.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free