Sharing our technical trials in terms of Ubuntu software installs, Blogger hacks, Android and Kotlin learning.
How to use control flow statements in Kotlin Cont’d
How to use control flow statements in Kotlin Cont’d

How to use control flow statements in Kotlin Cont’d

Control flow statements or Loops in Kotlin are used to carry out repetitive task’s by repeating certain set of code.

In our previous post about control flow statements we have covered “for” loop . This post which is a continuation we will be exploring “while” and “do..while” loops.

I. While Loop

Syntax:
while (condition) {
   //code goes here
}
  • starts with a keyword “while”
  • followed by brackets ( ) in which the condition for looping is mentioned
  • And the code that needs to be repeated as long as the condition satisfies is mentioned under { }
Example 1
 fun main (args:Array<String>)
{
     var x = 6
      while (x < 10)
      {
            println(x)
            x = x + 1
      }
}
Output

6
7
8
9

Explanation
  • The while loop checks for the condition, var x is less than 10
  • if the condition is satisfied the code mentioned inside { } would be executed
  • which in our case is to print the value of x and then increment it by one.
Example 2
 fun main (args:Array<String>)
{
      var x = 1
      while(x < 5)
      {
            println(x)    
      } 
}
Output

1
1……..

Explanation
  • The variable x is initialised before the loop starts and will always have the value one
  • as the condition satisfies all the time, the loop runs infinitely
Example 3

Boolean values can also be used in while loop

 fun main (args:Array<String>)
{
    var x = true
     while (x)
      {
            println(x)
            x = false
      }
}
Output

true

Explanation
  • As initially the variable is set to true, condition satisfies and the code block executes
  • after print statement as the variable is to set to false, code block doesn’t get executed

II. do..while Loop

Syntax:
do {
    //code to be executed 
} while (condition) // condition to be checked
  • keyword “do” followed by open and close braces { } – contains section of code that needs to be repeated as long as the condition satisfies
  • keyword “while” at the end mentioning the condition.
Example
 fun main (args:Array<String>)
{
    var x = 2
     do
     {
           println(x)
            x = x + 1
      } while (x < 5)
}
Output

2
3
4

Explanation
  • In case of do..while loop, the statements inside the loop is executed first and then the conditioned is checked
  • In our example the variable x is printed and incremented first then the condition is checked.

That brings us to the end of control flow statements, in our next post we will be seeing about conditional branching