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
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,
- The statements inside the body of the loop get executed.
- Then, the test expression is evaluated again and this process goes on until the test expression is evaluated to false.
If the test expression is evaluated to false,
- while loop gets terminated and control goes out of the while loop.
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,
1. i is initialized with value 1.
2. condition 1 < 4 is checked, yields true.
- “value of i: 1” gets printed.
- Updation is done. Now i = 2.
3. condition 2 < 4 is checked, yields true.
- “value of i: 2” gets printed.
- Updation is done. Now i = 3.
4. condition 3 < 4 is checked, yields true.
- “value of i: 3” gets printed.
- Updation is done. Now i = 4.
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