Lesson 2
Exploring Loops in Kotlin
Topic Overview

Greetings, Explorer! In this lesson, we will delve into the essential tools of Kotlin loops. Loops simplify and enhance the efficiency of repetitive tasks—much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring consistency. In this lesson, we will explore looping in Kotlin and gain hands-on experience by applying loops to Kotlin List and String.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop in Kotlin to print greetings for a group of friends.

Kotlin
1fun main() { 2 val friends = listOf("Alice", "Bob", "Charlie", "Daniel") 3 4 for (friendName in friends) { 5 // For each friendName, print the greeting 6 println("Hello, $friendName! Nice to meet you.") 7 } 8}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in Kotlin

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop in Kotlin can iterate over anything that is iterable, such as ranges or collections:

  1. Iterating over Ranges: You can iterate over a range using a simple syntax.
  2. Iterating over Collections: Iterate over elements in a List or similar collections directly.

Let's print a range of numbers using a for loop:

Kotlin
1fun main() { 2 for (num in 0 until 5) { 3 // This line prints numbers from 0 to 4 4 println(num) 5 } 6}

In each cycle of the loop, the variable num is automatically updated before executing the code inside the block.

Iterating Over Collections in Kotlin

The for loop in Kotlin can work with any iterable structure, such as strings and lists, providing a more straightforward and safe way to traverse these collections as it manages the loop variable automatically.

Kotlin
1fun main() { 2 // List of fruits 3 val fruits = listOf("apple", "banana", "cherry") 4 5 for (fruit in fruits) { 6 println(fruit) // prints each fruit 7 } 8}

In the above example, fruit stands for each element in the fruits list. The loop body executes once for each item in the fruits list, with fruit being the current element in each iteration.

Similarly, we may loop through strings, treating them as containers of characters:

Kotlin
1fun main() { 2 val word = "hello" 3 // 'ch' is each individual character in `word` 4 for (ch in word) { 5 println(ch) // prints each character from 'hello' 6 } 7}

In the example above, ch stands for each character in the word string. The loop repeats for each character, printing 'hello' one character at a time.

While Loop in Kotlin

While loops in Kotlin continuously execute their content until a particular condition becomes false. Here's a simple example:

Kotlin
1fun main() { 2 var num = 0 3 // The loop keeps running until num is no longer less than 5 4 while (num < 5) { 5 println(num) 6 // Increase num by 1 at the end of each iteration 7 num++ 8 } 9}

As you can see, before each iteration, Kotlin checks the condition (num < 5). If it's true, the loop continues; otherwise, the loop breaks.

Applications of Looping

Loops are integral to programming. They are extensively used in various sections of a program, such as summing elements in a list and parsing through text.

Kotlin
1fun main() { 2 // List of numbers 3 val numbers = listOf(1, 2, 3, 4, 5) 4 5 var total = 0 6 // `num` is each number in `numbers` 7 for (num in numbers) { 8 total += num // Add each number in the list 9 } 10 println(total) // Prints 15 11}
Kotlin
1fun main() { 2 val text = "hello" 3 var vowelCount = 0 4 // `ch` is each character in `text` 5 for (ch in text) { 6 // If a vowel letter is found, increment the count 7 if (ch in listOf('a', 'e', 'i', 'o', 'u')) { 8 vowelCount++ 9 } 10 } 11 println(vowelCount) // Prints 2 12}
Lesson Summary and Practice

Congratulations on mastering Kotlin loops! We've explored for and while loops and seen how to loop over collections like List and String. Now, it's time for some beneficial practice exercises to solidify your learning. The more problems you solve, the better you'll become. Let's proceed further on our journey into the depths of programming!

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