Android Question Nested for loops question

Devv

Active Member
Licensed User
Longtime User
May someone explain why this code make z equals 3 instead of 9 ?


B4X:
Sub Process_Globals
    Dim x,y,z As Int

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
    For x = 1 To 3
        For x = 0 To 2
            z = z +1
        Next
    Next
    
    Log("z :" & z)
End Sub
 

BillMeyer

Well-Known Member
Licensed User
Longtime User
The reason you get 3 is that you keep initializing "x" to a different value than expected in the 1st loop and you hinder the working of your first loop.

Essentially you have 2 loops both with the same variable "x". So for example, when your first loop reaches, for example 2, when it goes to the 2nd loop that x is now no longer 2 but now resets to 0. So when you break from the loop (they have completed running), z = 3.

All I have done is changed the second "x" to "y" (you have "Dim"ed it after all) and this should give the desired z = 9.

B4X:
Sub Process_Globals
    Dim x,y,z As Int

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
    For x = 1 To 3
        For y =  0 To 2 '<--- Change this from x to y for example and I would have made this 1 to 3 - just easier to read
            z = z + 1
        Next
    Next
    
    Log("z :" & z)
End Sub

This is untested code - so I'm trusting that my coding is OK.

As Mr Simpson would say: "Enjoy..."
 
Upvote 0
Top