Tuesday 12 December 2017

Kotlin Tutorials in Hindi | for loop



Kotlin in Hindi for Loop

The for loop in Kotlin iterates through anything that provides an iterator. In this article, you learn to create for loop (with the help of examples).
In Kotlin, for loop is used to iterate through ranges, arrays, maps and so on (anything that provides an iterator).
The syntax of for loop in Kotlin is:
for (item in collection) {
    // body of loop
}

Example: Iterate Through a Range

fun main(args: Array<String>) {

    for (i in 1..5) {
        println(i)
    }
}
Here, the loop iterates through the range and prints individual item.
When you run the program, the output will be:
1
2
3
4
5

If the body of the loop contains only one statement (like above example), it's not necessary to use curly braces { }.
fun main(args: Array<String>) {
    for (i in 1..5) println(i)
}

It's possible to iterate through a range using for loop because ranges provides an iterator. To learn more, visit Kotlin iterators.

Example: Different Ways to Iterate Through a Range

fun main(args: Array<String>) {

    print("for (i in 1..5) print(i) = ")
    for (i in 1..5) print(i)

    println()

    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i)             // prints nothing

    println()

    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)

    println()

    print("for (i in 1..4 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)

    println()

    print("for (i in 4 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)
}
When you run the program, the output will be:
for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) = 
for (i in 5 downTo 1) print(i) = 54321
for (i in 1..4 step 2) print(i) = 135
for (i in 4 downTo 1 step 2) print(i) = 531

Iterating Through a String

fun main(args: Array<String>) {

    var text= "Kotlin"

    for (letter in text) {
        println(letter)
    }
}
When you run the program, the output will be:
K
o
t
l
i
n

Similar like arrays, you can iterate through a String with an index. For example,
fun main(args: Array<String>) {

    var text= "Kotlin"

    for (item in text.indices) {
        println(text[item])
    }
}
When you run the program, the output will be:
K
o
t
l
i
n

No comments:

Post a Comment