Why write 100 lines of code when you can write 2? When we come across code we want to repeat, we can rely on loops. Loops give us the ability to repeat specified blocks of code as many times as we want.
Let’s say we wanted to output elements in a list. The process wouldn’t be that bad if the list had 5 elements. We could write five
println() statements. What if the list had 100 elements? Or 1,000? Or even 100,000?!
Loops answer the call when we need to repeat a task over and over again, even if it is millions of times.
In this lesson, we will look at loops that will repeat code a defined number of times or based on a specific condition. We will look at how to combine loops to obtain a higher number of repetitions as well as how to exit loops early or skip code repetitions.
By the end of this lesson you will understand the best way to repeat tasks in a controlled manner while keeping your code organized and readable.
Looking at the animation on the right, we can see that Codey is hiking through the Land of Loops. We use a type of Kotlin loop called
while to instruct Codey to continue to hike as long as
time < 18. Once
time is equal to
18, Codey will stop hiking and set up camp.
This is just one way to construct a loop, so just like Codey, let’s start our journey into the Land of Loops! Click Next to get started with loops using Kotlin.