Kotlin Do While Loop

Introduction

In programming, loops are essential structures that allow you to execute a block of code multiple times. Among the various types of loops, the do-while loop stands out because it guarantees that the code block will run at least once, regardless of the condition being true or false. This feature makes the do-while loop particularly useful in scenarios where you need to perform an action before checking a condition, like prompting a user for input.

When and Where Developers Use It

Developers often use do-while loops in situations where the code should run at least once before any condition is evaluated. For example, a do-while loop can be useful in user input validation or menu-driven applications where you want to show the menu at least once before checking if the user wants to continue.

Concept Explanation

What is a Do-While Loop?

A do-while loop is a control flow statement that executes a block of code, then checks the loop's condition. If the condition is true, the loop continues; if it's false, the loop stops.

Analogy

Think of it like a light switch in a room. When you enter, the light (the code) turns on first, and then you check if you want to stay in the room (the condition). Regardless of whether you want to stay or not, the light turns on first.

Comparison with Other Loops

Here's how a do-while loop compares to other looping constructs:

Feature While Loop For Loop Do-While Loop
Executes at least once No Depends on iteration Yes
Condition checked before execution Yes Yes No
Syntax structure while(condition) for(initialization; condition; increment) do { } while(condition)

Syntax

The syntax of a do-while loop in Kotlin is as follows:

Example

do {
    // body of do block
} while (condition)

Explanation of the Syntax

  • do: This keyword begins the do-while loop.
  • { }: The curly braces contain the block of code to be executed.
  • while: After executing the block, this keyword checks the condition.
  • (condition): This is the Boolean expression that, when true, keeps the loop running.
  • Working Examples

Let's explore several examples to understand how the do-while loop works.

Example 1: Basic Counting

In this example, we will print numbers from 1 to 5.

Example

fun main() {
    var counter = 1
    do {
        println(counter)
        counter++
    } while (counter <= 5)
}

Output:

Output

1
2
3
4
5

Example 2: User Input Validation

Here’s an example that prompts the user for a number until they enter a valid one (greater than zero).

Example

import java.util.Scanner

fun main() {
    val scanner = Scanner(System.`in`)
    var number: Int

    do {
        println("Please enter a positive number:")
        number = scanner.nextInt()
    } while (number <= 0)

    println("You entered: $number")
}

Output (Assuming the user enters -1 first and then 5):

Output

Please enter a positive number:
-1
Please enter a positive number:
5
You entered: 5

Example 3: Menu-Driven Program

In this example, we simulate a simple menu that allows users to choose an option to perform tasks.

Example

fun main() {
    var choice: Int
    
    do {
        println("Menu:")
        println("1. Perform Task 1")
        println("2. Perform Task 2")
        println("3. Exit")
        println("Enter your choice:")
        choice = readLine()!!.toInt()

        when (choice) {
            1 -> println("Task 1 executed.")
            2 -> println("Task 2 executed.")
            3 -> println("Exiting...")
            else -> println("Invalid choice, please try again.")
        }
    } while (choice != 3)
}

Output:

Output

Menu:
1. Perform Task 1
2. Perform Task 2
3. Exit
Enter your choice:
1
Task 1 executed.
Menu:
1. Perform Task 1
2. Perform Task 2
3. Exit
Enter your choice:
3
Exiting...

Example 4: Do-While with a False Condition

In this example, the loop will still execute once, even if the condition is false.

Example

fun main() {
    var number = 10
    do {
        println("Current number: $number")
        number++
    } while (number < 10)
}

Output:

Output

Current number: 10

Common Mistakes

Mistake 1: Forgetting the Condition

One common error beginners make is to forget to put the condition in the while statement. This leads to an infinite loop.

Incorrect Example:

Example

fun main() {
    var i = 1
    do {
        println(i)
        i++
    } while // missing condition
}

Correct Approach:

Make sure to always include a condition to avoid infinite loops.

Mistake 2: Incorrectly Placing the Condition

Another mistake is placing the condition within the do block instead of after.

Incorrect Example:

Example

fun main() {
    var i = 1
    do {
        println(i)
        i++
        while (i <= 5) // wrong placement
    }
}

Correct Approach:

Ensure the while condition is outside the do block.

Best Practices

  • Use Descriptive Names: When using loops, ensure the variable names are meaningful, like counter, choice, or number.
  • Avoid Infinite Loops: Always ensure that the loop has a condition that will eventually be false to prevent infinite looping.
  • Keep the Code Readable: Use proper indentation and spacing to make your code easier to read.
  • Limit Loop Complexity: If your loop needs to handle too many cases or complex logic, it might be worth refactoring it into a separate function.
  • Practice Exercises

  1. Even or Odd Checker: Create a program that prompts the user to enter numbers until they input a negative number. For each number entered, indicate whether it is even or odd.

Hint: Use a do-while loop to prompt for input.

  1. Password Validation: Write a program that asks the user to enter a password. The password must be at least 6 characters long. Keep prompting the user until a valid password is entered.

Hint: Remember to include the length check in the do-while loop condition.

  1. Guess the Number: Build a simple game where the computer randomly selects a number between 1 and 100. The user has to guess the number, and the program should tell them if their guess is too high, too low, or correct until they guess correctly.

Hint: Use a do-while loop to keep asking for guesses until the correct number is guessed.

Explore these exercises and enjoy coding!

Input Required

This code uses input(). Please provide values below:

🤖 Coding Mentor
🤖

Hi! I'm your coding mentor

Ask me anything about programming:

• Python, Java, C++, JavaScript

• Algorithms & Data Structures

• Debugging & Code Help