Hello and welcome to today's journey into loops in Kotlin! Imagine you've been assigned the task to count the trees in your area. Will you do it individually? That's not efficient, right? That's where loops come to the rescue, saving both time and effort by automating repetitive tasks. Kotlin offers two types of loops, for and while. Our focus today is on for loops, which are used when the number of repetitions is known.
Let's start with the for loop. It's an orderly and efficient way of accomplishing tasks repetitively in Kotlin. If you have a list of names and want to print them, you can use the for loop:
Every iteration of the loop picks a new name from names and prints it.
Are you ready to explore for loops further? Kotlin provides the flexibility to denote ranges that define a start and end value. To print numbers from 1 to 5, you can do:
To execute a loop in reverse, we can use the downTo keyword:
It's time to practice! If you want to print the numbers 1 through 10 and all elements of an array, refer to the example below:
In a for loop, if you want to access the index along with the value:
Remember these tips as they'll enhance your coding efficiency:
- Don't alter the collection you're looping over within the loop.
- Variables declared within a loop only exist (or in programmer lingo, are "scoped") within the loop.
Consider this:
Our innerValue is scoped inside the loop, so trying to print it outside would throw an error.
In Kotlin, loops can be written in a concise form without braces ({}) for single statements. This is particularly useful for simple iterations:
However, this concise form cannot be used when multiple statements are involved in the loop's body. Attempting to do so without using curly braces {} will result in incorrect syntax or unintended behavior:
Kotlin simplifies the creation of value ranges, offering an intuitive syntax for defining sequences of numbers or characters:
Congratulations! You're now acquainted with for loops in Kotlin. The upcoming practice sessions will help you sharpen your for loop skills and reinforce your understanding. Let's dive in!
