Google News
logo
Kotlin - Interview Questions
Explain the various methods to iterate over any data structure in Kotlin with examples.

Following are the different ways to iterate over any data structure in Kotlin :

For Loop : The for loop is used to scan any data structure that supplies an iterator in this case. It is not used in the same way as the for loop in other programming languages such as Java or C.

In Kotlin, the for loop has the following Syntax :
for(item in collection) {
     // code
}​
Here, collection refers to the data structure to be iterated and item refers to each element of the data structure.

Example :
fun main(args: Array<String>) {
   var numbersArray = arrayOf(1,2,3,4,5,6,7,8,9,10)
 
   for (num in numbersArray){
       if(num % 2 == 0){
           print("$num ")
       }
   }
}

Output :
2 4 6 8 10​


While Loop : It is made up of a code block and a condition to be checked for each iteration. First, the while condition is assessed, and if it is true, the code within the block is executed. Because the condition is verified every time before entering the block, it repeats until the condition turns false. The while loop can be thought of as a series of if statements that are repeated.

The while loop's syntax is as follows :
while(condition) {
         // code
}​
Example :
fun main(args: Array<String>) {
   var number = 1
   while(number <= 5) {
       println(number)
       number++;
   }
}​
Output  :
1
2
3
4
5​

Do While Loop : The condition is assessed after all of the statements inside the block have been executed. If the do-while condition is true, the code block is re-executed. As long as the expression evaluates to true, the code block execution procedure is repeated. The loop ends if the expression becomes false, and control is passed to the sentence following the do-while loop. Because it verifies the condition after the block is executed, it's also known as a post-test loop.

The do-while loop's syntax is as follows :
do {
     // code
{
while(condition)​
Example :
fun main(args: Array<String>) {
   var number = 4
   var sum = 0
 
   do {
       sum += number
       number--
   }while(number > 0)
   println("Sum of first four natural numbers is $sum")
}​
Output :
Sum of first four natural numbers is 10​
Advertisement