Loops in Kotlin

Learn via video courses
Topics Covered

Overview

Loops in Kotlin are like repeating instructions in a game. Imagine you have to do something multiple times. Loops in Kotlin like a for loop is like counting numbers in order. A while loop is like doing something as long as a condition is true. A do-while loop is like doing something once, and then checking if you should do it again. You can also use break to stop the loop early, and continue to skip a step and move to the next one. Loops help you avoid doing the same thing over and over manually.

Introduction

Loops in Kotlin are like helpers for doing things again and again. The for loop is like a recipe you follow a certain number of times, like baking cookies a few rounds. While loop is a rule: keep going as long as something's true, like playing until tired. Do-while loop is like trying a cool skateboard move at least once, then more if fun.

Loops in Kotlin have break (quick exit) and continue (skip a step) buttons. Break is like leaving a line that's too long. Continue is like skipping a puzzle piece that's not right. These tools help coders manage repeat jobs smartly.

Kotlin For Loops

Kotlin's for loops are like a helpful tour guide for going through a list of things. They show you each item in the list one by one, so you can do something with them. It's like checking off tasks on a to-do list. You start at one end, look at each task, and finish when you've seen them all. It can iterate through different types of data, like ranges, arrays, and maps, as long as they can provide an iterator.

Range

In Kotlin, you can use a for loop to iterate through a range of values. Here's an example of how to do it:

In this example, the for loop iterates through the range of values from start to end, including both endpoints. The .. operator is used to create a range. If you want to iterate through a range with a different step, you can use the step keyword:

In this case, the loop will iterate through the range from start to end with a step size of step. we can also use an integer directly without using a val for it

Array

Let's understand this through an example, we have defined an array called fruits containing various fruit names. We then demonstrate three different methods to iterate through the array:

  1. Using a basic for loop with the index.
  2. Utilizing the indices property to iterate through the array indices.
  3. Using the withIndex() function to simultaneously get the index and the element.

Each method produces the same output, iterating through the array and displaying the fruit names along with their respective indices.

Output

String

You can iterate through a string in Kotlin just like you would with an array. Let's see an example of iterating through a string using different methods:

Output

Collection

Iterating through a collection in Kotlin involves using a for loop. For each element in the collection, the loop executes a defined block of code. This allows you to access and process each item individually, simplifying tasks like printing or modifying data. Let's understand this through an example:

Output

In this example, we have defined a list called items containing various items. We then use a for loop to iterate through each item in the list and print it.

Kotlin while Loop

The Kotlin while loop repeatedly executes a block of code while a specified condition holds true. It checks the condition before each iteration, allowing dynamic control over loop execution. This loop type is useful for iterating until a particular state is met, promoting efficient and controlled code flow. The syntax of a while loop in Kotlin is as follows:

Flowchart

This simplified flowchart represents the fundamental structure of a while loop:

  1. Start: The loop begins.

  2. Condition: Check if the specified condition is true.

  3. Is Condition True?: If the condition is true, proceed to the next step.

  4. Execute Loop Body: Execute the code block within the loop.

  5. Update: Perform any necessary updates or modifications.

  6. Check Condition: Go back to step 3 and repeat the process if the condition remains true.

  7. Exit Loop: If the condition becomes false, exit the loop.

  8. Exit: The loop concludes.

while loop flowchart

Example

Output

The code initializes a variable count at 0 and enters a while loop while count is below 5. If count is 2, the loop skips the rest of that iteration using continue. The loop prints count unless it's 2. If count is 4, the loop breaks. Afterward, "Loop finished" is printed.

Kotlin do-while Loop

The Kotlin do-while loop ensures the execution of a code block before checking a condition. The loop continues executing as long as the condition remains true, providing a guaranteed first iteration. This construct is useful when you want to execute code at least once while still checking a condition for subsequent iterations.The syntax of a do-while loop in Kotlin is as follows:

Flowchart

This flowchart outlines the key steps of a do-while loop:

  1. Start: The loop begins.

  2. Execute Loop Body: Execute the code block within the loop at least once.

  3. Update: Perform any necessary updates or modifications.

  4. Condition: Check if the specified condition is true.

  5. Is Condition True?: If the condition is true, proceed to step 3 and repeat the loop.

  6. Exit Loop: If the condition becomes false, exit the loop.

  7. Exit: The loop concludes.

do while loop flowchart

Example

In this example, the do-while loop guarantees that the loop body is executed at least once, regardless of the condition. It prints the current count, increments it, and then checks if the count is still less than or equal to 5. The loop continues as long as the condition is true. After the loop finishes, a message is printed to indicate its completion.

Output

Conclusion

  • Kotlin is a versatile and modern programming language that offers concise syntax and powerful features.
  • It supports a variety of loops, including for, while, and do-while, providing flexibility in iterating and controlling program flow.
  • The for loop simplifies iteration through ranges, collections, and arrays.
  • while loops execute code while a given condition holds true, ensuring dynamic control over iterations.
  • do-while loops guarantee at least one execution of the loop body, making them suitable for situations requiring an initial run before condition checking.
  • Proper loop usage enhances code readability, performance, and maintenance.
  • Developers can choose the most suitable loop type based on specific requirements and iteration scenarios.