Friday 15 December 2017

Kotlin: for loop

‘for’ loop is used to iterate over a collection, array, ranges etc.,

By using ‘for’ loop, you can iterate over anything that provides iterator.

Looping through arrays
Syntax
for(ele in array){

}

ArrayDemo.kt
fun main(args: Array<String>) {

 var arr: Array<Int> = arrayOf(2, 3, 5, 7)

 for(ele in arr){
  println(ele)
 }
}

Output
2
3
5
7

Loop over a range
ArrayDemo.kt
fun main(args: Array<String>) {

 for(ele in 1..10){
  println(ele)
 }
}

Output
1
2
3
4
5
6
7
8
9
10

Loop over a string
ArrayDemo.kt

fun main(args: Array<String>) {

 var message = "Good Morning"
 
 for(c in message){
  print(c)
 }
}

Output

Good Morning



Previous                                                 Next                                                 Home

No comments:

Post a Comment