Tutorials

Loops in Kotlin Made Simple: for, while, and do-while

Loops in Kotlin Made Simple: for, while, and do-while

Loops are an essential part of programming, helping developers perform repetitive tasks efficiently without rewriting code multiple times. In Kotlin, loops allow you to automate actions like iterating through numbers, processing lists, or performing calculations. By using loops, programs become cleaner, faster, and easier to maintain. Kotlin offers three main types of loops, for, while, and do-while, each designed for different scenarios. Understanding how and when to use each loop is key to writing effective and readable code.

The for loop is ideal for iterating over ranges, arrays, or collections, making it simple to access elements and indices. The while loop runs as long as a specified condition is true, which is useful when the number of repetitions is unknown. The do-while loop guarantees that the code executes at least once before checking the condition, making it perfect for tasks like input validation or menu-driven programs. This article aims to explain these loops in a simple, beginner-friendly way, with clear examples and practical tips. By the end, you will understand how to use loops in Kotlin effectively and apply them to solve real programming problems.

Understanding the for Loop in Kotlin

The for loop in Kotlin is a core control structure used to execute a block of code repeatedly. It is especially useful for iterating through ranges, arrays, and collections in a clean and concise way. Unlike traditional loops in some languages, Kotlin’s for loop relies on the in keyword, allowing direct traversal of elements without requiring manual indexing. You can easily loop through a range using for (i in 1..5), or iterate over a list of items. Additionally, it supports custom iteration with step and downTo, making it versatile for both ascending and descending sequences.

Syntax and Usage

The basic syntax of a for loop in Kotlin is simple:

for (i in 1..5) {
    println(i)
}

In this example, the variable i takes values from 1 to 5, and the loop executes five times. Kotlin also provides flexible options for controlling iteration. The until keyword allows the loop to exclude the last number in a range, which is useful when zero-based indexing or exclusive ranges are needed. Additionally, the step keyword lets you skip values during iteration. For instance, for (i in 1..10 step 2) iterates through 1, 3, 5, 7, and 9.

Iterating Collections

The for loop is excellent for working with arrays, lists, and other collections. It allows you to iterate through each element directly using for (item in list), which makes the code clean, concise, and highly readable. The loop works efficiently with both mutable and immutable collections, ensuring flexibility in different scenarios. Overall, the for loop offers a simple yet powerful way to process, navigate, and manage elements effectively within Kotlin’s versatile data structures.

Key advantages include:

  • Using for (item in list) for direct and clean iteration.
  • Using for ((index, value) in list.withIndex()) to access both index and value.
  • Removing the need for manual counters, improving code clarity.

For example:

val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
    println(fruit)
}

You can also include the index if needed:

for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}

Practical Applications

For loops are commonly used when you know the exact number of iterations or need to traverse a collection. They can be applied to tasks such as processing user input, performing calculations over numeric ranges, or manipulating elements in a list. In real-world programming, for loops simplify repetitive tasks, making the code more concise, readable, and efficient. Developers often rely on them when working with data sets, iterating through arrays, or automating calculations. For example, they can be used to validate multiple entries in a form, calculate the sum or average of numbers in a list, or generate patterns and sequences in a program. They are also valuable in simulations, game development, and handling repetitive logic such as updating scores, printing tables, or cycling through options.

  • Iterating over arrays, lists, or other collections.
  • Working with numeric ranges where the number of repetitions is fixed.
  • Implementing tasks that require a predictable sequence of operations.

In summary, Kotlin’s for loop is a versatile and powerful control structure that saves time, reduces errors, and helps manage structured data effortlessly. Its flexibility allows developers to focus on logic instead of manually managing counters, ensuring clean, maintainable, and bug-free code.

Understanding the while Loop

The while loop in Kotlin is used to repeatedly execute a block of code as long as a specified condition is true.
It checks the condition before each iteration, so the loop may not run at all if the condition is initially false.
This makes it ideal for scenarios where the number of repetitions is unknown.
while loops are flexible and can handle dynamic situations like reading user input or monitoring a process.
Care must be taken to update variables inside the loop to avoid infinite loops.
Overall, it provides a simple way to perform repeated tasks based on conditions in Kotlin.

What is a while Loop?

A while loop repeats a block of code as long as a specified condition remains true. It checks the condition before every iteration, meaning the loop may not run at all if the condition is false from the start. This makes it especially useful for situations where the number of repetitions is unknown or depends on user input or program state. Unlike the for loop, which is suited for fixed ranges, the while loop offers greater flexibility for dynamic conditions. Common examples include reading data until the end of a file, prompting users until valid input is given, or running a process until a specific event occurs. Because the loop automatically stops when the condition becomes false, it helps prevent infinite execution if conditions are well-defined.

  • A while loop repeats a block of code as long as a condition is true.
  • It checks the condition before each iteration.
  • Ideal for situations where the number of repetitions is unknown.
  • Provides flexibility over for loops for dynamic conditions.
  • Stops executing automatically when the condition becomes false.

Syntax and Structure

  • The basic syntax includes a condition and a code block:
var i = 1
while (i <= 5) {
    println(i)
    i++
}
  • The condition is evaluated before every iteration.
  • The loop executes repeatedly only if the condition is true.
  • Variables affecting the condition must be updated inside the loop.
  • Curly braces {} are used to enclose the code that needs repetition.

Practical Examples

  • Reading user input until a valid response is entered.
  • Counting numbers until a certain limit is reached.
  • Monitoring real-time processes until a stop condition occurs.
  • Repeating a task until an external event triggers completion.
  • Performing operations where the iteration depends on runtime data.

Common Mistakes

  • Forgetting to update the loop variable → leads to infinite loops.
  • Incorrect condition logic → loop may never run or run endlessly.
  • Placing code outside the loop that should repeat → logical errors.
  • Modifying variables incorrectly inside the loop → unexpected results.
  • Ignoring exit conditions → can freeze or crash the program.

When to Use while Loops

  • When the number of iterations is not known in advance.
  • For conditional execution based on dynamic program states.
  • When looping depends on user input or external data.
  • For repeating tasks until a specific event or flag occurs.
  • When flexibility is needed to stop the loop anytime during runtime.

Understanding the do-while Loop

The do-while loop in Kotlin is a type of loop that executes a block of code at least once before checking a condition. This is the main difference from the while loop, which evaluates the condition first and may not execute at all if the condition is false initially. The do-while loop is especially useful in scenarios where an action must occur at least once, such as prompting user input, displaying menus, or performing operations that require initial execution before verification. It is commonly applied in validation checks, retry mechanisms, and user-driven tasks where guaranteed execution is essential. Additionally, it enhances program interaction by ensuring users always see an output before deciding the next step, making applications more user-friendly.


What is a do-while Loop?

  • Executes a code block once before checking the condition.
  • Ensures the loop body runs at least once, even if the condition starts as false.
  • Suitable for tasks that require an initial action before validating conditions.
  • Similar to a while loop but differs in execution order.
  • Often used for interactive programs, user prompts, or runtime-dependent tasks.
  • Prevents premature termination by guaranteeing initial execution, making it ideal for menus, password checks, or retry mechanisms.

A do-while loop is especially useful when developers want to guarantee user interaction or process execution before a condition is validated, ensuring smoother and more predictable program behaviour.


Syntax and Structure

The do-while loop syntax in Kotlin is simple:

var i = 1
do {
    println(i)
    i++
} while (i <= 5)
  • The code block is written inside the do { ... } braces.
  • The condition follows the block and is checked after execution.
  • If the condition evaluates to true, the loop repeats; otherwise, it stops.
  • Loop variables must be updated inside the loop to avoid infinite loops.
  • Guarantees at least one execution of the loop body.

Practical Examples

  • Console menu selection – Display a menu at least once for user choice:
var choice: Int
do {
    println("1. Start\n2. Settings\n3. Exit")
    choice = readLine()!!.toInt()
} while (choice !in 1..3)
  • User input validation – Ensure input is prompted at least once:
var age: Int
do {
    println("Enter your age:")
    age = readLine()!!.toInt()
} while (age <= 0)
  • Retry operations – Perform tasks repeatedly until success.
  • Interactive applications – Execute a task at least once before checking conditions.
  • Processing runtime data – For situations requiring initial execution prior to validation.

When to Use do-while Loops

  • When the code must execute at least once regardless of the condition.
  • For input validation, such as forms, passwords, or numeric entries.
  • Displaying interactive menus in console or GUI programs.
  • Repeating tasks until success or exit conditions are met.
  • When execution depends on dynamic runtime data rather than fixed iterations.

The do-while loop is a simple yet powerful structure that ensures code runs at least once before checking conditions, making it perfect for interactive programs, user input validation, and scenarios requiring initial execution. Its unique post-condition check sets it apart from other loops like for and while.

Comparison of Loops

Loops are a fundamental aspect of Kotlin programming, enabling developers to repeat tasks efficiently and reduce redundancy. Each type of loop—for, while, and do-while—has its own unique characteristics and best use cases. The for loop is ideal for fixed iterations over ranges, arrays, or collections where the number of repetitions is known. The while loop continues execution as long as a condition remains true, offering flexibility when the number of iterations is uncertain. The do-while loop guarantees that the code runs at least once, making it particularly useful for input validation or menu-driven programs. By understanding these differences, programmers can choose the most appropriate loop, write cleaner and more maintainable code, and handle a wide variety of programming tasks with greater precision and efficiency.

for Loop

  • Executes a block of code a fixed number of times.
  • Ideal for iterating over ranges, arrays, and collections.
  • Condition is implicit, based on the start and end of the range.
  • Easy to use when the number of iterations is known beforehand.
  • Supports features like step (to skip values) and until (to exclude the last value).

Example:

for (i in 1..5) {
    println(i)
}

This loop prints numbers 1 to 5 sequentially, making it predictable and efficient for fixed iteration tasks.


while Loop

  • Executes a block of code as long as a condition is true.
  • Checks the condition before each iteration, so it may not run at all if the condition is false initially.
  • Suitable for scenarios where the number of repetitions is unknown.
  • Requires careful handling of loop variables to avoid infinite loops.
  • Flexible for dynamic or runtime-dependent tasks, such as reading input until a valid value is entered.

Example:

var i = 1
while (i <= 5) {
    println(i)
    i++
}

do-while Loop

  • Executes a block of code at least once, regardless of the condition.
  • Checks the condition after the code block, ensuring one guaranteed execution.
  • Ideal for tasks like user input validation or interactive menus.
  • Also useful for retrying operations until a success or exit condition occurs.
  • Provides reliability when initial execution must happen before condition checking.

Example:

var i = 1
do {
    println(i)
    i++
} while (i <= 5)

Key Differences

  • for loops are fixed and predictable.
  • while loops are conditional and may not execute if the condition is false initially.
  • do-while loops always execute once before checking the condition.

Choosing the right loop depends on the task: use for for fixed iterations, while for conditional repetition, and do-while when at least one execution is required. By understanding these differences, Kotlin developers can write clean, efficient, and reliable code.

  • For Loop → Best suited for cases where the number of iterations is known in advance, such as iterating through arrays, lists, or numeric ranges. It simplifies structured tasks like processing items in a shopping cart or generating tables.
  • While Loop → Effective when the repetition depends on dynamic conditions, such as reading input until the user enters “exit.” It provides flexibility in handling unpredictable tasks.
  • Do-While Loop → Ensures the code block runs at least once, making it ideal for menus, password checks, or repeated prompts where at least one attempt is guaranteed.

Conclusion

Loops are an essential part of Kotlin programming, enabling developers to execute repetitive tasks efficiently and reduce redundant code. The for loop is ideal for situations with a known number of iterations, making it perfect for iterating over ranges, arrays, and collections. In contrast, the while loop provides flexibility, as it continues execution only while a condition is true, which is useful when the number of repetitions cannot be determined in advance. Meanwhile, the do-while loop guarantees that the code block executes at least once, making it particularly suitable for interactive tasks such as user input validation or menu-driven applications. By understanding how each loop works, developers can select the most appropriate type for their task, ensuring cleaner, structured, and more efficient code that adapts well to different real-world programming challenges.

Mastering loops is more than just learning syntax—it is about controlling the flow of a program and handling dynamic situations effectively. Using loops correctly allows programmers to automate repetitive operations, respond to runtime conditions, and write logic that is both reliable and readable. Whether for beginners or experienced Kotlin developers, loops form a foundational skill that enhances problem-solving, optimizes performance, and builds the backbone of functional, interactive, and responsive applications across a wide range of practical use cases.


.

You may also like...