E
E
Ekaterina Kulchitskaya2021-04-27 16:46:29
Kotlin
Ekaterina Kulchitskaya, 2021-04-27 16:46:29

I'm trying to figure out how nested loops work. I’ve been solving the problem for several days and I can’t understand why in the answer X = 81 and y = 23?

fun main(args: Array) {
var y = 20
var x = 0
for(outer in 1..3) {
for (inner in 4 downTo 2) {
x += 6

y++
x += 3
}
y -= 2
}
println("$x $y")
}

I solve the problem, the answer is x = 81 y = 23 I can't figure out how the loop works

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-04-27
@keny1994

Is it clear now?

fun main() {
    var y = 20
        var x = 0
        for (outer in 1..3) {
            println("outer before $x $y")
            for (inner in 4 downTo 2) {
                println("	inner before $x $y")
                x += 6
                y++
                x += 3
                println("	inner after $x $y")
            }
            y -= 2
            println("outer after $x $y")
        }
        println("$x $y")
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question