0
0
Kotlinprogramming~5 mins

Repeat function for simple repetition in Kotlin

Choose your learning style9 modes available
Introduction

The repeat function helps you run the same code multiple times easily without writing a loop manually.

When you want to print a message several times.
When you need to perform a task repeatedly, like retrying a connection.
When you want to fill a list or array with repeated values.
When you want to run a block of code a fixed number of times for testing.
Syntax
Kotlin
repeat(times: Int) {
    // code to repeat
}

times is how many times the code inside will run.

The code inside the curly braces runs each time, from 0 up to times-1.

Examples
This prints "Hello" three times.
Kotlin
repeat(3) {
    println("Hello")
}
This prints the count from 0 to 4 using the index variable.
Kotlin
repeat(5) { index ->
    println("Count: $index")
}
Sample Program

This program prints the phrase "Kotlin is fun!" four times using repeat.

Kotlin
fun main() {
    repeat(4) {
        println("Kotlin is fun!")
    }
}
OutputSuccess
Important Notes

You can use the optional index parameter inside the repeat block to know which repetition you are on.

Repeat is a simple and clean way to avoid writing loops when you know the exact number of repetitions.

Summary

The repeat function runs code a set number of times.

It makes repeating tasks easy and clean without manual loops.

You can access the current repetition count with an index if needed.