Search code examples
for-loopgonested-loops

i tried 2 style of nested loop in golang, but it has different output


i have this quiz, you should make an output like this, and i search youtube tutorials for "for golang" and it explain that it has 2 style of for in golang,

1 21 11 12 13 14 22 11 12 13 14 23 11 12 13 14 24 11 12 13 14 2 21 11 12 13 14 22 11 12 13 14 23 11 12 13 14 24 11 12 13 14 3 21 11 12 13 14 22 11 12 13 14 23 11 12 13 14 24 11 12 13 14 4 21 11 12 13 14 22 11 12 13 14 23 11 12 13 14 24 11 12 13 14 5 21 11 12 13 14 22 11 12 13 14 23 11 12 13 14 24 11 12 13 14

it should be vertically outputted, not horizontally, so i build 3 variable, i = 1, j = 21, and k = 11, and i use for to automatically increase the value, the 1st style worked, but the 2nd style somehow its different

yt vid : https://www.youtube.com/watch?v=jZ-llP_yKNo on 5:28 min he explain that for has 2 style

1st style :

for i:=1; i <= 5; i++{
        fmt.Println(i)
        for j:=21; j <= 24; j++ {
            println(j)
            for k:=11; k<=14; k++ {
                fmt.Println(k)
            }
        }
    }

2nd style :

i:=1
j:=21
k:=11

for i <= 5{
    fmt.Println(i)
    i++
    for j <= 24 {
        println(j)
        j++
        for k<=14 {
            fmt.Println(k)
            k++
        }
    }
}

Solution

  • It's not about the syntax but about your logic.

    In the 1st style with for i := ..., whenever next loop run, you reset the value to the init state, means it always sets j to 21 and k to 11. So there will a many sub loop runs.

    In contrast, 2nd style, you init value j and k right before going to loop. So in the second loop of i, j and k are still the same value with 25 and 15 in that order.