Nested for loops

Trying to learn js I found this on the internet but I don’t understand a thing.


    for (var i=1; i<4; i++) {
        for (var k=1; k<4 - i; k++) {
            document.write(k + " first ");
        }
        for (var j=1; j<=i; j++) {
             document.write(j + " second ");
        }
        document.write(i + " OUTER Loop<br> ");
    }

OUTPUT:

1 first 2 first 1 second 1 OUTER Loop
 1 first 1 second 2 second 2 OUTER Loop
 1 second 2 second 3 second 3 OUTER Loop

My question is why do I have only 2 first on the first line and not 3?
My logic was:
i=1 < 4 good
k=1 <4-1 good (4-1 = 3) print 3 times first

Because on the first line i=1, that means k<4-1 = k<3, so k will only have values 1 and 2

2 Likes

Thank you very much for your explanation.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.