Start learning free

LESSON 114 OF 348 · WHILE LOOPS & FOR LOOPS

Why Loops in Kotlin: Repeating Code Without Copying It

Lesson Read the full explanation

Loops are probably the most powerful tool a programming language can offer. You can run the same code multiple times by using a loop.

To really understand their value, let’s take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.

Imagine this: A student made a mistake and the teacher asked them to print I made a mistake 5 times to the console.

If we only use println(), our program might look like this:

println("I made a mistake")
println("I made a mistake")
println("I made a mistake")
println("I made a mistake")
println("I made a mistake")

That’s ugly, but still manageable. After all, we’re writing only 5 lines of code and most probably copying and pasting a few times.

Now imagine if we come back to this program and we wanted to print the message for 10, 100, 100000 times? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We’ll learn how loops come to our rescue in the next lesson. But for now, let’s gain an appreciation for loops.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · WHILE LOOPS & FOR LOOPS

    Why Loops in Kotlin, explained

    The problem loops solve

    Programs often do the same thing many times: print a line for every item in a list, add up a column of numbers, check every character of a string. Without a way to repeat code, you would have to write each repetition yourself.

    Suppose a teacher asks a student to print I made a mistake five times. With only println, the program looks like this:

    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    

    Each call prints its text followed by a line break, so five calls give five lines. It is dull, but it works, and for five lines nobody minds copying and pasting.

    Why this does not scale

    The trouble starts when the number changes. Printing the message 10 times means five more copies. Printing it 100 times means 100 lines of code, and 100,000 times is not realistic at all. The cost grows with the number of repetitions, and so do the chances of a mistake:

    • Too many or too few copies. Counting lines by eye is unreliable. With 100 identical lines, it is hard to tell whether you wrote 99 or 101.
    • Inconsistent edits. If the message changes later, you have to change every copy. Fixing 99 of the 100 lines leaves one stale line in the output.
    • Unreadable code. A reader has to count the lines to learn how many times something runs, and a count that lives in how many lines you wrote isn't written down anywhere.
    • The count can't depend on data. If the program must repeat something once per item in a list, and the list has a different length each time, no fixed number of copied lines can be right.

    The last point is the most important. Real programs rarely know in advance how many times they must repeat something, and copied lines are fixed when you write the code.

    What a loop does instead

    A loop runs a block of code repeatedly, and the code is written once. You state what to repeat and how long to keep going, and the language does the counting. To print the message a thousand times, only the number changes, not the amount of code.

    Kotlin has several kinds of loops, and you will meet them in the next lessons:

    • the while loop, which repeats as long as a condition is true;
    • the for loop, which goes through the elements of an array, a list or a range of numbers.

    For example, the five-line program above can later be written with repeat(5) { println("I made a mistake") }, which prints the same five lines. Changing 5 to 100 is a one-character edit.

    The exercise

    This lesson deliberately avoids loops, to show the problem they solve. The task is to print I promise to learn coding. five times using only println.

    1. Write one statement that prints the sentence: println("I promise to learn coding.").
    2. Repeat it on five lines. Each call prints one line, so five calls give five lines.
    3. Match the text exactly. The sentence ends with a period, and capital letters and spaces count. A copy with a different character prints a different line.
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    

    Notice how it feels to write this. Now imagine the task is 50 lines, with the sentence changed halfway through. That discomfort is the reason loops exist.

    Key takeaways

    • Repeating code by copying it works for a few lines and breaks down quickly after that.
    • Copies are easy to miscount and easy to update inconsistently.
    • A loop lets you write the code once and say how many times, or for which items, it runs.
    • Kotlin's main loops are while and for.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free