Lesson 1
Exploring For Loops in Kotlin: A Beginner's Guide
Understanding Loop Structures

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.

Introduction to 'For' Loop in Kotlin

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:

Kotlin
1fun main() { 2 // Our list of names 3 val names = listOf("John", "Sarah", "Jane", "Tom") 4 5 // Our 'for' loop 6 for (name in names) { 7 println(name) // Prints each name in the list 8 } 9}

Every iteration of the loop picks a new name from names and prints it.

Variations of 'For' Loop in Kotlin

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:

Kotlin
1fun main() { 2 // Loop from 1 to 5 and print each number 3 for (i in 1..5) { 4 println(i) // Outputs numbers 1 through 5 5 } 6}

To execute a loop in reverse, we can use the downTo keyword:

Kotlin
1fun main() { 2 // Loop from 5 to 1 3 for (i in 5 downTo 1) { 4 println(i) // Outputs numbers 5 to 1 in descending order 5 } 6}
'For' Loop in Action

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:

Kotlin
1fun main() { 2 // Loop to print numbers 1 through 10 3 for (num in 1..10) { 4 println(num) // Prints numbers 1 to 10 5 } 6 7 // Loop to iterate through an array 8 val numbers = arrayOf(1, 2, 3, 4, 5) 9 for (n in numbers) { 10 println(n) // Prints numbers 1 to 5 11 } 12}

In a for loop, if you want to access the index along with the value:

Kotlin
1fun main() { 2 // Our list of names 3 val names = listOf("John", "Sarah", "Jane", "Tom") 4 5 // Loop through the list withIndex() 6 for ((index, value) in names.withIndex()) { 7 println("The element at $index is $value") // Prints index and corresponding name 8 } 9 10 // Alternatively you can use .indices property to get a valid index range for array 11 for (i in names.indices) { 12 println("The element at $i is ${names[i]}") // Prints index and corresponding name 13 } 14}
Variable Scopes

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:

Kotlin
1fun main() { 2 // Loop over a range of numbers 3 for (i in 1..3) { 4 val innerValue = "hello" // Declare a variable in the loop 5 } 6 println(innerValue) // Error! innerValue is out of the scope 7}

Our innerValue is scoped inside the loop, so trying to print it outside would throw an error.

Shorthand Loop Syntax

In Kotlin, loops can be written in a concise form without braces ({}) for single statements. This is particularly useful for simple iterations:

Kotlin
1for (i in 1..3) println("Loop iteration: $i") // Directly prints each iteration 2 3var outsideVar = 0 4for (i in 1..3) outsideVar = i // Updates an externally declared variable 5println("Last updated value: $outsideVar") // Correctly prints: Last updated value: 3

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
1// Attempting multiple statements without braces - This will cause an error 2for (i in 1..3) println("Iteration: $i") val squared = i * i println("Squared: $squared")
Cheat Sheet for Kotlin Ranges

Kotlin simplifies the creation of value ranges, offering an intuitive syntax for defining sequences of numbers or characters:

Kotlin
1 1..4 // 1, 2, 3, 4 2 1 until 4 // 1, 2, 3 3 4 downTo 1 // 4, 3, 2, 1 4 0..8 step 2 // 0, 2, 4, 6, 8 5 8 downTo 0 step 2 // 8, 6, 4, 2, 0
Lesson Summary and Upcoming Practice

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.