Home » Kotlin

Looping statements in Kotlin programming language



In this tutorial we will learn about Looping statements like for loop, while loop and do while loop with examples.
Submitted by Aman Gautam, on December 02, 2017

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)





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.