Kotlin Loops

In this tutorial you will learn about the Kotlin Loops and its application with practical example.

Kotlin Loops

In Kotlin, loops statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. In Kotlin Programming Language we have following loops –

  • Kotlin for loop
  • Kotlin forEach statement
  • Kotlin repeat statement
  • Kotlin while loop
  • Kotlin do..while loop

Kotlin for Loop

The for loop takes a collection of data(ranges, arrays, collections, or anything that provides an iterator) and iterate through the items one at a time in sequence.

Syntax:-

Example:-

Output:-

Kotlin while Loop

The while loop will execute a block of statement as long as a test expression is true.

Syntax:-

Example:-

Output:-

Kotlin forEach statement

forEach can be used to repeat loop statement for each element in given collection.

Example:-

Output:-

Kotlin repeat statement

Kotlin repeat statement is used to execute a set of statements for N-number of times.

Example:-

The following program prints “Hello World!” 5 times

Output:-

Kotlin do…while Loop

The do…while statement executes loop statements and then test the condition for next iteration and executes next only if condition is true.

Syntax:-

Example:-

Let’s see a simple example of do-while loop printing “Hello World!” for 5 times.

Output:-

 

In this tutorial we have learn about the Kotlin Loops and its application with practical example. I hope you will like this tutorial.