InterviewSolution
Saved Bookmarks
| 1. |
Explain the various methods to iterate over any data structure in Kotlin with examples. |
|
Answer» Following are the different WAYS to iterate over any data structure in Kotlin :
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. For example, // KOTLINfun 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
The while loop's syntax is as follows: while(condition) { // code }For example, // KOTLINfun main(args: Array<String>) { var number = 1 while(number <= 5) { PRINTLN(number) number++; }}Output - 12345
The do-while loop's syntax is as follows: do { // code {while(condition)For example, // KOTLINfun 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 |
|