Often when you work with arrays, you need to loop through all of the elements.To loop through array elements, use the for loop together with the in operator:Example Output all elements in the cars array: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") for (x in cars) { ...
1. Iterate over elements of an array In the following program, we take an array of strings, and iterate over the elements of this Array. Inside For Loop, we print the element. Main.kt </> Copy fun main(args: Array<String>) { val arr = arrayOf("apple", "banana", "cherry") for...
Loop Through an Array Often when you work with arrays, you need to loop through all of the elements. You can loop through the array elements with theforloop, which you will learn even more about in the next chapter. The following example outputs all elements in thecarsarray: ...
A for loop iterates through the elements of a collection. So, it does not behave like a for statement in a language like C/C++, but more like a foreach statement in C#. The basic format of a for statement is like this. 代码语言:javascript 代码运行次数:0 运行 AI代码解释 for (element...
* See http://kotlinlang.org/docs/reference/control-flow.html#while-loops */ fun main(args: Array<String>) { var i = 0 while (i < args.size) println(args[i++]) } /** * For loop iterates through anything that provides an iterator. * See http://kotlinlang.org/docs/reference/...
fun main(args:Array<String>){ println("Hello,World!") } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 包的声明处于源文件顶部。这里,我们声明了包 com.easy.kotlin , 里面定义了包级函数 what() , 同时定义了一...
As the factor will remain the same in all the rows, we’ll have to loop through two multiplier and result variables. Further, we’ll need two ranges in our loop. While the first range will hold the list of multipliers corresponding to different rows, on the other hand, the second range...
fun main(args:Array<String>){val myArray=arrayOf("Steve","Robin","Kate","Lucy")for(ninmyArray.indices){println("myArray[$n]: ${myArray[n]}")}} Output: Function withIndex() in for loop In the above example we have iterated through the array using array indices. Another way of ...
There are three types of loops in kotlin – for loop, while loop, and do-while loop. Let’s discuss them one by one. 1. For loop in kotlin Kotlin for loop is used to iterate the program several times. It iterates through ranges, arrays, collections, or anything that provides for ite...
iteration through a range会被编译优化,无须创建额外对象。 可用withIndex库函数实现index迭代 for((index,value)inarray.withIndex()){println("the element at $index is $ value")} 查看for循环语法 While循环 while 和 do..while while(x>0){x--}do{valy=retrieveData()}while(y!=null)// a little...