C1CTech

Kotlin while Loop

In this article, you will learn about while loop and how to create while loop in Kotlin programming.

Loops in Kotlin are used when we want to execute a block of statements repeatedly until a specific condition is met(condition is false).

Kotlin While Loop

The while loop executes the block of code as long as a specified condition is true.

Syntax

//while loop

//test-expression is a boolean expression
while (test-expression) {
   
   // body of the loop
   //statements to be executed
}

Flowchart of while Loop

Screenshot 2020-03-18 14.21.18

How while loop works?

When the Control falls into the while loop, it first checks the test_expression.

If the test expression is evaluated to true,

If the test expression is evaluated to false,

Example 1

fun main(args: Array<String>) {

    var i = 1

    //exit when i becomes greater than 3
    while (i < 4) {
        println("value of i: $i")

        //increment value of i by 1
        i++
    }
}

Output

value of i: 1
value of i: 2
value of i: 3

Example explained

In the above example,

1i is initialized with value 1.

2. condition 1 < 4 is checked, yields true.

3. condition 2 < 4 is checked, yields true.

4. condition 3 < 4 is checked, yields true.

5. condition 4 < 4 is checked, yields false.

6. exit from the while loop.

Example 2

The below program will print the sum of natural numbers from 1 to 10.

fun main(args: Array<String>) {

    var i = 1
    var sum = 0

    // Exit when i becomes greater than 10
    while (i <= 10) {
        sum = sum + i   

        //Increment the value of i for
        //next iteration
        i++
    }
    println("Sum of numbers from 1 to 10: $sum")
}

Output

Sum of numbers from 1 to 10: 55
Exit mobile version