user3251969
user3251969

Reputation: 162

Why does nested for-next loops give weird results

I'm confused of my nested for-next loops results.My Question is how does the computer read this function and come up with this result. I understand it reads up to down, but that would give me a result of 1,4,2,3,3,2,1. My result is wrong and I don't understand how the computer gets the real result.

When you have: for outsideloop = 1, 3, 1 do print (outsideloop) end

It prints out 1,2,3

When you have: for insideloop = 4, 1, -1 do -- inside loop print (insideloop) end

Now when you have the insideloop nested inside the outside loop you get:

for outsideloop = 1, 3, 1 do -- outside loop

print (outsideloop)

for insideloop = 4, 1, -1 do -- inside loop

    print (insideloop)
end
end

with a result of 1, 4, 3, 2, 1, 2, 4, 3, 2, 1, 3, 4, 3, 2, 1

This last result is my confusion. Can someone clear up my confusion.

Upvotes: 1

Views: 94

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263467

Here's a modified version of your program that might clarify what's going on. I've modified your program so the numbers printed by the inner loop are indented.

#!/usr/bin/lua

for outsideloop = 1, 3, 1 do -- outside loop
    print (outsideloop)
    for insideloop = 4, 1, -1 do -- inside loop
        print ("", insideloop)
    end end

The output is:

1
        4
        3
        2
        1
2
        4
        3
        2
        1
3
        4
        3
        2
        1

The numbers printed by the outer loop are 1, 2, and 3, in that order.

The numbers printed by the inner loop are 4, 3, 2, and 1, in that order -- and the inner loop is executed 3 times, once for each iteration of the outer loop.

Upvotes: 4

nerraruzi
nerraruzi

Reputation: 98

The output is correct.

  1. outsideloop starts its first iteration with a value of 1
  2. outsideloop is printed, hence printing 1
  3. First iteration of insideloop starts, which gives 4
  4. insideloop is printed, hence printing 4
  5. Second iteration of insideloop starts, which is 3
  6. insideloop is printed, hence printing 3
  7. and insideloop continues printing 2 and 1
  8. Second iteration of outsideloop starts at 2
  9. outsideloop is printed, hence printing 2
  10. insideloop runs again, printing 4 all the way down to 1(steps 3 to 7)
  11. Third iteration of outsideloop starts
  12. outsideloop is printed, hence printing 3
  13. insideloop runs once more

Hope I could help!

Upvotes: 3

Related Questions