Search code examples
loopsfor-loopwhile-loopnestednested-loops

Differences between loops and nested loops in kotlin


fun main(args: Array<String>) {
    val books = arrayListOf("farenheit 451", "1984", "Altered Carbon", "dark matter", "Le probleme à trois corps")
    for (book in books) {
        if (book.contains('e')) {
            println(book)
        }
    }
}

Why does this print this result:

farenheit 451
Altered Carbon
dark matter
Le probleme à trois corps

when this :

fun main(args: Array<String>) {
    val books = arrayListOf("farenheit 451", "1984", "Altered Carbon", "dark matter", "Le probleme à trois corps")
    for (book in books) {
        if (book.contains('e')) {
            for(l in book){
                println(l)
            }
        }
    }
}

print each character individually ?

I think i know, but not sure : The first loop will itterate over each element, therefor printing books name line by line.

while in the second scenario, the nested loop itterate over each char of each element

Am i getting this correctly ?


Solution

  • Yes, you are absolutely correct; books is a collection of strings, whereas book is a single string.

    Because you cannot iterate over a single string, you're instead asking to iterate over each individual character (letter) of the string.

    So you will loop over the books, farenheit 451 will pass the conditional, and thus l will be f, a, r and so on for each iteration. 1984 will be skipped over as it does not pass the conditional, and not be looped over. Altered Carbon will then pass the conditional, so will have each of its characters looped over.