Looping statements in Kotlin programming language

By IncludeHelp Last updated : December 04, 2024

Looping Statements

Looping statements are required when set of statements to be executed respectively until given condition is not satisfied.

There are 3 loops in Kotlin

  1. The for loop
  2. The while loop
  3. The do while loop

The for loop

for loop is used to repeat a piece of code several time. for loop has been redesigned in Kotlin. It mostly looks like for each loop in java or C#. It operates through anything that provides an iterator.

Syntax

for (item in collection) 
  print(item)
  . . . .

Example

for(i in 1..10){       // similar to for(int i=1; i<=10; i++)
  print(i)
}

printing elements of array

for (i in arr.indices) {
  print(arr[i])
}

Alternatively, we can also use withIndex() library function,

for ((index, value) in arr.withIndex()) { 
  println("element at $index is $value")
}

The while loop

This is looping statement, in which condition is checked at the entry of the statement, that’s why it is also called entry controlled loop. If the condition is true then statements inside the block will execute and if condition is false then control goes outside the body of the loop.

Syntax

while(condition){
    . . . .
    statements
    . . . . 
}

Example

var x=10
while(x>0){
  print(x)
  x--
}

The do while loop

This is an exit controlled loop. In this, condition is checked at the end of block after executing the statements. So in this all statements will execute at least once even the condition is false. The syntax for do while loop is given below,

Syntax

do{
    . . . .
    statements
    . . . .
}
while(condition)

Example

var x=10
do{
  print(x)
}while(x>0)

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.