Start learning free

LESSON 118 OF 348 · WHILE LOOPS & FOR LOOPS

Why loops? in Rust

Lesson

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

    Why Loops in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free