Home > Net >  Kotlin For loop, confused
Kotlin For loop, confused

Time:07-05

Does anyone explain how it works? X and Y answer explain, please. Answer: 81 and 23

fun main(args: Array<String>) {
    var x =0
    var y =20

    for (outer in 1..3) {

        for (inner in 4 downTo 2) {
            x  = 6
            y  
            x  = 3
        }

        y -= 2
    }

    println("$x $y")
}

CodePudding user response:

You can follow the steps with inserted print statements. For x it would like this:

var x = 0
for (outer in 1..3) {
  for (inner in 4 downTo 2) {
    x  = (6   3)
    println("outer: $outer | inner: $inner | x: $x")
  }
  println()
}
println("x: $x")

Output:

outer: 1 | inner: 4 | x: 9
outer: 1 | inner: 3 | x: 18
outer: 1 | inner: 2 | x: 27

outer: 2 | inner: 4 | x: 36
outer: 2 | inner: 3 | x: 45
outer: 2 | inner: 2 | x: 54

outer: 3 | inner: 4 | x: 63
outer: 3 | inner: 3 | x: 72
outer: 3 | inner: 2 | x: 81

x: 81

Same for y:

var y = 20
for (outer in 1..3) {
  for (inner in 4 downTo 2) {
    y  
    println("outer: $outer | inner: $inner | y: $y")
  }
  y -= 2
  println("outer: $outer | y: $y")
  println()
}
println("y: $y")

Output:

outer: 1 | inner: 4 | y: 21
outer: 1 | inner: 3 | y: 22
outer: 1 | inner: 2 | y: 23
outer: 1 | y: 21

outer: 2 | inner: 4 | y: 22
outer: 2 | inner: 3 | y: 23
outer: 2 | inner: 2 | y: 24
outer: 2 | y: 22

outer: 3 | inner: 4 | y: 23
outer: 3 | inner: 3 | y: 24
outer: 3 | inner: 2 | y: 25
outer: 3 | y: 23

y: 23

CodePudding user response:

you have start variables of x = 0 and y = 20. the outer loop is run 3 times and the inner loop is run 3 times in the outer loop. So the functions in the inner loop gets called 9 times and the functions in the outer loop (y-=2) is run 3 times.

x = 0 (9 * (6 3)) = 81

y = 20 9 (3 * -2) = 23

  • Related