Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop in kotlin [closed]

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]) } 
like image 380
Sundeep Badhotiya Avatar asked Feb 07 '18 12:02

Sundeep Badhotiya


People also ask

How does for loop work in Kotlin?

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.

How do I stop for loop Kotlin?

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.

How do you restart a loop in Kotlin?

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.


2 Answers

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

like image 53
AskNilesh Avatar answered Oct 10 '22 10:10

AskNilesh


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())     } 
like image 42
IntelliJ Amiya Avatar answered Oct 10 '22 10:10

IntelliJ Amiya