2 Replies Latest reply: Jan 13, 2019 4:36 AM by Tomas RSS

    Nested for loops

    Tomas

      Hi.

       

      I started PRNE v.1.0 video course and have stumbled upon one code snipped which does not make sense to me:

       

       

      What is output by the following code?

       

      x = 0

      for y in range(0, 5):

        for z in range(0, 5):

          x = x + y + z

      print x

       

      The correct answer is 100 and I don't understand how it comes to such value?

       

      "y" in range(0, 5) will be "0, 1, 2, 3, 4" and "z" in range(0, 5) will be "0, 1, 2, 3, 4"

       

      What's not clear to me, is what am I supposed to do with "0, 1, 2, 3, 4" - should i add each individual item to each other, or should i multiply them, or what?

       

      Whatever arithmetic thing i do unto them, i dont get 100 lol

        • 1. Re: Nested for loops
          Phoenix

          Hi Tomas,

           

          In nested for loop, program first encounters the outer loop (here its Loop Y ), executing its first iteration.This first iteration triggers the inner, nested loop (it's Z loop here), which then runs to completion.Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop.


          Here, at first iteration, Y=0 and it will execute next line that is another loop.

               now, z will set value 0, complete the addition,loop ends..

               next iteration, z=1, complete the code and z increments..

               ....this inner loop will continue to do the job until z reaches 4. when z=4 it will complete that code and terminates the loop (as z range from 0 to 5, i.e 0 <5)

           

          Inner loop terminates, and now, execution go back to outer loop once again, and this time Y=1 and executes next line

               we're once again in z loop, z=0...x=x+y+z

               z=1.....

               z=4

           

          Again, Y=2,

                    z=0...4

           

          So ,this is how actually nested loop works..

           

          You can check this intermediate value to understand how this loop running.. here is the modified code

           

          x=0
          for y in range(0,5):

             for z in range(0,5):

                  print("Inner Loop")

                  print("value of z", z)

                 x=x+y+z

                  print ("Value of x", x)

           

             print("Outer Loop")

             print("Value of Y", y)


          print("Both loop ends...........")

          print ("Final Result:" , x)

             

             

           

          Hope this helps.. :-)

          • 2. Re: Nested for loops
            Tomas

            Thank you Phoenix, that modified code really helped