Kotlin While Loop

While loop are used to iterates group of statement until given condition expression result is not invalid or false. This loop are check first expression result, and according to result iterates and terminates.

while loop flowchart
while(expression){
  //loop statements (body of loop)
  //increment or decrement termination condition
  }

For example

fun main(args: Array<String>) {
   val dataText:String="Kotlin Programmer";
   var index:Int=0;
   var length:Int=dataText.length //get length of string
   while(index<length){
      //display string char by index
    println("${dataText[index]}");
    index++;//increment index by one
   }
}

Output

K
o
t
l
i
n
 
P
r
o
g
r
a
m
m
e
r

While loop execution concept is completely based on termination condition. if terminate conditional is logically incorrect then in this situations can be possible to iterate loop in infinite times. see the example of infinite loop.

fun main(args: Array<String>) {

   var index:Int=1;
   //not a valid logical condition
   while(index>0){
      print(index)
   }
}

Output

printed 1  infinite

So try to set valid condition to terminate loop.

Example of While loop

In this example mention of few examples how to use while loop in diffrent different situations.

fun main(args: Array < String > )
{
    var i = 1;
    val j = 10;
    // When (i) less than j
    while (i <= j)
    {
        // Display the table element
        println(i * j);
        // increase i value by one
        i++;
    }
}

Output

10
20
30
40
50
60
70
80
90
100

Other example calculate the factorial of a number.

fun main(args: Array < String > )
{
    val num = 4;
    var i = 1;
    var result = 1;
    // When (i) less than j
    while (i <= num)
    {
        result *= i;
        // increase i value by one
        i++;
    }
    println(result);
}

Output

24


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved