1. *** New version of B4J is available ***
    B4J v7.8
    Dismiss Notice

Android Question Nested for loops question

Discussion in 'Android Questions' started by Devv, Aug 21, 2019.

  1. Devv

    Devv Active Member Licensed User

    May someone explain why this code make z equals 3 instead of 9 ?


    Code:
    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
     
  2. BillMeyer

    BillMeyer Active Member Licensed 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.

    Code:
    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..."
     
  3. AnandGupta

    AnandGupta Active Member Licensed User

    Devv you need a rest, seriously.

    It happens to me too :)

    Regards,

    Anand
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice