For Loop in Kotlin with Examples | Kotlin For Loop

 

For loop in Kotlin


In this post, we will know about the for loop in Kotlin. Kotlin for loop used to iterate the given array or list. For loop in Kotlin by default increase the iterative index values by 1. This called a step. We can define the value step.


In some cases, we have to only iterate even numbers. In that case, the manual definition of the step is very important.


Kotlin for loop is very helpful for programmers. Whenever programmers want to iterate the whole list. In that case for loop is very helpful.


Syntax of For loop in Kotlin


for( conditions){
//statements
//statements

}


Examples of For loop in Kotlin

//Program to print first ten natural numbers using for loop in Kotlin

For Loop in Kotlin


Output

For Loop in Kotlin


Print vs Println in Kotlin


Have you noticed one thing? Here we used println instead of print. Now the question arises why? Because in Kotlin print is used to print the statement. And the cursor remains on the same line in Kotlin. 


But in the case of println. It prints the statement and moves the cursor to the next line. So whenever you want to print the statement on the next line. Then use the println method.


Example


#Print even number using for loop in Kotlin

The number that is divisible by 2. And the remainder is zero is called an even number.


fun main() {
    for( i in 0..10 step 2){
        println(i)
    }
}

Output

For Loop in Kotlin

#Print even number using for loop in Kotlin


The number that is not divisible by 2. And the remainder is not  equal to zero is called an odd number.


fun main() {
    for( i in 1..10 step 2){
        println(i)
    }
}

Output

For Loop in Kotlin

#Print the numbers in descending order using for loop in Kotlin


To prints the reverse range. Here we used the downTo keyword.


fun main() {
    for( i in 10 downTo 1){
        println(i)
    }
}


Output

For Loop in Kotlin

#String iteration using for loop in Kotlin

fun main() {

    val arr = arrayOf("Ram","Shyam","Ali","Jack")

    for( i in arr){

        println(i)
    }

}

Output

Ram
Shyam
Ali
Jack

Post a Comment