Reputation: 162
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
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
Reputation: 98
The output is correct.
Hope I could help!
Upvotes: 3