You are here
Home > Kotlin

Kotlin Loops

loops in kotlin

Kotlin Loops

In this post, we will discuss loops in kotlin with example. Same as all other languages kotlin also support three loops while, for, do-while.

Loops

  • Same as all other languages kotlin also has three types of loops: for, while, do-while. Loops are used to execute some code many number of times.

While Loop

  • While loop is entry control loop. Means it check the condition before executing the loop. Its syntax is same as all other languages.

Syntax:
While(condition)
{
//loop body
} 
Example:
fun main(args:Array<String>)
{
//while loop
var count = 1;
while (count < 5)
{
if (count == 2) {
println(“count is 2”)
}
count++;
}
}

output:

 

For loop

  • For loop is also entry control loop. For iteration through for loop we use in operator. It is only use with for loop.
  • For loop is also use with ranges.
  • We can also nest for loop like in c or java.

Syntax:
For(var_name in range)
{
//loop body
}
Example:
fun main(args:Array<String>)
{
//simple for loop
for(i in 1..2)
{
println(“count”+i);
}
//nested for loop
for (j in 1..2)
{
for(k in 2..4)
{
println(“multi=”+(j*k));
}
}
}
output:

Do-while loop

  • Do-while loop is exit control loop means loop is executed at-least once if condition is fail.

Syntax:
do
{
//loop body
} while(condition)
Example:
fun main(args:Array<String>)
{
println(“do while loop”);
var i=4;
do
{
println(“i=”+i);
i–;
}while (i>=1)
}
output:

Break

  • In any programming language, sometimes we required to terminate loop without checking condition.
  • At that time, we use break It terminates the nearest enclosing loop.

Example:
fun main(args:Array<String>)
{
for(i in 1..5)
{
if(i==4)
break;
println(“i=”+i);
}
}
output:

Explanation:
We create for loop that print 1 to 5 number. We have to terminate the loop when i=4, so provide condition in if statement. Break statement terminates loop if i==4.

Continue

  • Sometime we require to skip some iteration while using loop at that time use continue
  • The Continue statement skip current iteration and jump to the next iteration.

Example:
fun main(args:Array<String>)
{
for(i in 1..5)
{
if(i==4)
continue;
println(“i=”+i);
}
}
output:

Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info.

You can also by SQL 70-761 book write by me from Amazon.

You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Leave a Reply

Top