C
C#2w ago
Hampta

✅ Can someone explain how this works?

Heres the code
No description
14 Replies
Hampta
HamptaOP2w ago
in Lua, which i used before, this would be done like this
for i=2, 10, 3 do
print(i) -- 2, 5, 8, 11
end
for i=2, 10, 3 do
print(i) -- 2, 5, 8, 11
end
so i dont get why it only outputs 3 numbers?
ero
ero2w ago
is 11 <= 10?
🕊 ILoveBirds 🕊
it prints 3 numbers because your i variable starts at 2, and your condition is i <= 10 or until it reaches 10, and each loop ur adding += 3 to ur i variable first loop prints 2 since your starting from i=2 then ur adding += 3 to i, so it becomes 5 next again adding += 3, turns 5 into 8, and adding another 3 would break the loop since it has reached 10
ero
ero2w ago
this kinda omits the fact that the i <= 10 check is done before entering the loop body, not after which i assume is where they're confused
🕊 ILoveBirds 🕊
yea I was a little confused too at first until I did a little test didn't know u could i+=3 instead of i++
ero
ero2w ago
you can have any expression there
🕊 ILoveBirds 🕊
I see
ero
ero2w ago
you can even do for (; true; SomeMethod()) or for (;;)
ティナ
ティナ2w ago
testing in lua, only three numbers printed so i think they just make a mistake or forget what actually happen
🕊 ILoveBirds 🕊
if ur using lua, heres a doc explaining the for loop syntax
Hampta
HamptaOP2w ago
tysm guys, i understand it now.

Did you find this page helpful?