Kotlin While Loop

Kotlin While Loop

Kotlin While loop is used to execute a block of code repeatedly based on a condition.

Syntax

The syntax of a While loop is

while (condition) {
  // body
}

where

  • while is keyword.
  • ( is the syntax to define the start of condition.
  • condition is an expression that evaluates to a boolean value.
  • ) is the syntax to define the end of condition.
  • { denotes the start of the While loop body.
  • } denotes the end of the While loop body.

Between curly braces, you can write the body of the While loop.

Examples

1. Print “Hello World” five times

In the following program, we use While loop to print “Hello World” five times.

Kotlin Program

fun main(args: Array<String>) {
    var i = 0
    while (i < 5) {
        println("Hello World")
        i++
    }
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World

2. Print numbers from 1 to n

In the following program, we use While loop to print integers from 1 to n.

Kotlin Program

fun main(args: Array<String>) {
    val n = 10

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

Output

1
2
3
4
5
6
7
8
9
10