I am new in Kotlin, Please help me in achieving this.
int number[] = {5,4,1,3,15} for(int i = number.length; i > 0; i--) { Log.e("number", number[i]) }
Unlike Java and other programming languages, there is no traditional for loop in Kotlin. In Kotlin, the for loop is used to loop through arrays, ranges, and other things that contains a countable number of values. You will learn more about ranges in the next chapter - which will create a range of values.
The break statement is used to terminate the loop immediately without evaluating the loop condition. As soon as the break statement is encountered inside a loop, the loop terminates immediately without executing the rest of the statements following break statement.
You can use a labeled outer while loop. By using continue on the outer loop, you restart your iteration. You can put break after the outer iteration so we can exit the while loop when complete.
Try this
syntax of for
loop in Kotlin
is:
for (item in collection) { // body of loop }
body
for (item: Int in ints) { // body of loop }
SAMPLE CODE
for (i in 0..5) { println(i) // 0,1,2,3,4,5 --> upto 5 }
OR
for (i in 0 until 5) { println(i) // 0,1,2,3,4 --> upto 4 }
for loop in array
var arr = arrayOf("neel", "nilu", "nilesh", "nil") for (item in arr) { println(item) }
iterate through an array with an index.
var arr = arrayOf("neel", "nilu", "nilesh", "nil") for (item in arr.indices) { // printing array elements having even index only if (item%2 == 0) println(language[item]) }
for more information check for loop in Kotlin
and this also for loop in Kotlin
Read Control Flow Structure in Kotlin
.
for (item in collection) print(item)
for
loop iterates through anything that provides an iterator. This is equivalent to the foreach
loop.
The body can be a block.
for (item: Int in ints) { // ... }
Try with
val number = arrayOf(5, 4, 1, 3, 15) for (i in 0 until number.size) { Log.e("NUMBER", number[i].toString()) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With