Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Nested loops

Nested loops

Scheduled Pinned Locked Moved The Lounge
questionlounge
74 Posts 34 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    Lost User
    wrote on last edited by
    #1

    Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

    for(int i=0; i<100; i++) { //Okay
    for(int j=0; j<100; j++) { //Acceptable
    for(int k=0; k<100; k++) { //Messy
    }
    }
    }

    S S T R L 22 Replies Last reply
    0
    • L Lost User

      Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

      for(int i=0; i<100; i++) { //Okay
      for(int j=0; j<100; j++) { //Acceptable
      for(int k=0; k<100; k++) { //Messy
      }
      }
      }

      S Offline
      S Offline
      Slacker007
      wrote on last edited by
      #2

      I don't like to go past two but I rarely run into a situation that would make me think of more.

      "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
      "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)

      1 Reply Last reply
      0
      • L Lost User

        Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

        for(int i=0; i<100; i++) { //Okay
        for(int j=0; j<100; j++) { //Acceptable
        for(int k=0; k<100; k++) { //Messy
        }
        }
        }

        S Offline
        S Offline
        Simon_Whale
        wrote on last edited by
        #3

        for me personally if you are at a point of needing to deeper than two levels then you need to rethink the approach

        Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

        F S 2 Replies Last reply
        0
        • L Lost User

          Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

          for(int i=0; i<100; i++) { //Okay
          for(int j=0; j<100; j++) { //Acceptable
          for(int k=0; k<100; k++) { //Messy
          }
          }
          }

          T Offline
          T Offline
          TheGreatAndPowerfulOz
          wrote on last edited by
          #4

          That's just silly. Use as many nested loops as required for the algorithm and no more. It may be possible to re-factor and re-engineer the algorithm to make fewer loops, but that may make the code more complex, and harder to understand. Judicious use of The KISS principle is, I think, best.

          If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
          You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

          R L B S F 5 Replies Last reply
          0
          • L Lost User

            Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

            for(int i=0; i<100; i++) { //Okay
            for(int j=0; j<100; j++) { //Acceptable
            for(int k=0; k<100; k++) { //Messy
            }
            }
            }

            R Offline
            R Offline
            R Giskard Reventlov
            wrote on last edited by
            #5

            Two.

            "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

            N 1 Reply Last reply
            0
            • T TheGreatAndPowerfulOz

              That's just silly. Use as many nested loops as required for the algorithm and no more. It may be possible to re-factor and re-engineer the algorithm to make fewer loops, but that may make the code more complex, and harder to understand. Judicious use of The KISS principle is, I think, best.

              If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
              You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

              R Offline
              R Offline
              R Giskard Reventlov
              wrote on last edited by
              #6

              Personally think if you're going deeper than 2 your design may need looking at though I wholeheartedly agree with and have always extolled the virtues of KISS. :thumbsup:

              "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

              1 Reply Last reply
              0
              • R R Giskard Reventlov

                Two.

                "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

                N Offline
                N Offline
                Nagy Vilmos
                wrote on last edited by
                #7

                What if you want to iterate over a 3D space plotting each x,y,z in a different colour?


                Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                E R T 3 Replies Last reply
                0
                • T TheGreatAndPowerfulOz

                  That's just silly. Use as many nested loops as required for the algorithm and no more. It may be possible to re-factor and re-engineer the algorithm to make fewer loops, but that may make the code more complex, and harder to understand. Judicious use of The KISS principle is, I think, best.

                  If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
                  You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  ahmed zahmed wrote:

                  That's just silly.

                  No, it's not.

                  ahmed zahmed wrote:

                  It may be possible to re-factor and re-engineer the algorithm to make fewer loops

                  That's the whole point of making this post. :-) I've seen loops neck deep where the reviewer would find commiting suicide easier than coming out of it.

                  T S 2 Replies Last reply
                  0
                  • L Lost User

                    Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

                    for(int i=0; i<100; i++) { //Okay
                    for(int j=0; j<100; j++) { //Acceptable
                    for(int k=0; k<100; k++) { //Messy
                    }
                    }
                    }

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    for (int index = 0; index < 1000000; index++)
                    {
                    int k = index % 100;
                    int j = (index / 100) % 100;
                    int i = index / 10000;
                    }

                    Don't think so. That might be the worst possible way to do it.

                    for (int i = 0; i < 100; i++)
                    {
                    innerLoop(i);
                    }

                    Great. So you thought you found the actual logic? Nope, Chuck Testa a useless outer loop that tells you nothing about what's going on. This might work if you have code bubbles[^], but otherwise it's like you have to keep turning stones one by one until you finally find the interesting part. It's probably the "accepted way" anyway, but it sucks. Any possible way to do this sucks. Fortunately it's not very common.

                    F 1 Reply Last reply
                    0
                    • L Lost User

                      ahmed zahmed wrote:

                      That's just silly.

                      No, it's not.

                      ahmed zahmed wrote:

                      It may be possible to re-factor and re-engineer the algorithm to make fewer loops

                      That's the whole point of making this post. :-) I've seen loops neck deep where the reviewer would find commiting suicide easier than coming out of it.

                      T Offline
                      T Offline
                      TheGreatAndPowerfulOz
                      wrote on last edited by
                      #10

                      Making an arbitrary rule to have no more than one nested loop (two loops) *is* indeed a silly rule. See here[^] for an example where your arbitrary rule makes no sense. Your data structures, or database, or whatever may require more looping. Unrolling such loops usually results in harder-to-understand and often less efficient code. It may not be possible to re-engineer or re-factor the code without redoing the entire system. Often an unachievable goal for legacy and cost reasons. If this is a new system, then yeah, by all means go for it, if possible and truly better. I have found that often, it's not really better. See

                      If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
                      You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

                      A 1 Reply Last reply
                      0
                      • N Nagy Vilmos

                        What if you want to iterate over a 3D space plotting each x,y,z in a different colour?


                        Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                        E Offline
                        E Offline
                        Espen Harlinn
                        wrote on last edited by
                        #11

                        Then you might be playing around with a point cloud, which sounds kind of fun :-D For anything non-trivial you would usually end up using an octree, which you would probably generate by looping over each dimension ...

                        Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS My LinkedIn Profile

                        1 Reply Last reply
                        0
                        • L Lost User

                          Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

                          for(int i=0; i<100; i++) { //Okay
                          for(int j=0; j<100; j++) { //Acceptable
                          for(int k=0; k<100; k++) { //Messy
                          }
                          }
                          }

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #12

                          I would tend to refactor the loops into smaller methods so that I can follow it easier:

                          public void IterateOverRoadNetwork(RoadSegments[] segments)
                          {
                          foreach (RoadSegment segment in segments)
                          {
                          CheckNetworkSpeeds(segment);
                          }
                          }
                          public void CheckNetworkSpeeds(RoadSegment segment)
                          {
                          foreach (Vehicle vehicle in segment.Vehicles)
                          {
                          CheckForImpossibleRoute(vehicle);
                          }
                          }
                          public void CheckForImpossibleRoute(Vehicle vehicle )
                          {
                          foreach (VehicleRestriction restriction in vehicle.Restrictions)
                          {
                          //
                          }
                          }

                          By doing this, I can name methods for their intent, so I can see what they are trying to do. That's my preferred option.

                          *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                          "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                          My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                          H S 2 Replies Last reply
                          0
                          • P Pete OHanlon

                            I would tend to refactor the loops into smaller methods so that I can follow it easier:

                            public void IterateOverRoadNetwork(RoadSegments[] segments)
                            {
                            foreach (RoadSegment segment in segments)
                            {
                            CheckNetworkSpeeds(segment);
                            }
                            }
                            public void CheckNetworkSpeeds(RoadSegment segment)
                            {
                            foreach (Vehicle vehicle in segment.Vehicles)
                            {
                            CheckForImpossibleRoute(vehicle);
                            }
                            }
                            public void CheckForImpossibleRoute(Vehicle vehicle )
                            {
                            foreach (VehicleRestriction restriction in vehicle.Restrictions)
                            {
                            //
                            }
                            }

                            By doing this, I can name methods for their intent, so I can see what they are trying to do. That's my preferred option.

                            *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                            "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                            My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                            H Offline
                            H Offline
                            hairy_hats
                            wrote on last edited by
                            #13

                            If that's in your satnav you must have to drive really slowly for all those nested function calls to complete before you arrive at wherever you wanted it to direct you to.

                            P F 2 Replies Last reply
                            0
                            • N Nagy Vilmos

                              What if you want to iterate over a 3D space plotting each x,y,z in a different colour?


                              Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                              R Offline
                              R Offline
                              R Giskard Reventlov
                              wrote on last edited by
                              #14

                              a) good point. b) never had to do anything like that so don't really care. c) Two: anything else is lunacy and must be stamped out: 2 dimensions is more than enough for anybody!

                              "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

                              T N V S 4 Replies Last reply
                              0
                              • R R Giskard Reventlov

                                a) good point. b) never had to do anything like that so don't really care. c) Two: anything else is lunacy and must be stamped out: 2 dimensions is more than enough for anybody!

                                "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

                                T Offline
                                T Offline
                                TheGreatAndPowerfulOz
                                wrote on last edited by
                                #15

                                OK, then, stay where you are. I'll be bringing my steamroller over. Please lay on the ground. Afterwards, you will be two-dimensional.

                                If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
                                You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

                                1 Reply Last reply
                                0
                                • L Lost User

                                  Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

                                  for(int i=0; i<100; i++) { //Okay
                                  for(int j=0; j<100; j++) { //Acceptable
                                  for(int k=0; k<100; k++) { //Messy
                                  }
                                  }
                                  }

                                  T Offline
                                  T Offline
                                  thatraja
                                  wrote on last edited by
                                  #16

                                  Depends

                                  thatraja

                                  FREE Code Conversion VB6 ASP VB.NET C# ASP.NET C++ JAVA PHP DELPHI ColdFusion
                                  HTML Marquee & its alternatives

                                  Nobody remains a virgin, Life screws everyone :sigh:

                                  T 1 Reply Last reply
                                  0
                                  • H hairy_hats

                                    If that's in your satnav you must have to drive really slowly for all those nested function calls to complete before you arrive at wherever you wanted it to direct you to.

                                    P Offline
                                    P Offline
                                    Pete OHanlon
                                    wrote on last edited by
                                    #17

                                    Or, it could be the routine that precalculates all the routes and filters out the impossible to pass roads for different vehicle sizes and types, when you load a road network into a database.

                                    *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                                    "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                                    My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                                    1 Reply Last reply
                                    0
                                    • T thatraja

                                      Depends

                                      thatraja

                                      FREE Code Conversion VB6 ASP VB.NET C# ASP.NET C++ JAVA PHP DELPHI ColdFusion
                                      HTML Marquee & its alternatives

                                      Nobody remains a virgin, Life screws everyone :sigh:

                                      T Offline
                                      T Offline
                                      TheGreatAndPowerfulOz
                                      wrote on last edited by
                                      #18

                                      Do you use them? I feel sorry for you... ;P ;P

                                      If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
                                      You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun

                                      1 Reply Last reply
                                      0
                                      • R R Giskard Reventlov

                                        a) good point. b) never had to do anything like that so don't really care. c) Two: anything else is lunacy and must be stamped out: 2 dimensions is more than enough for anybody!

                                        "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair. nils illegitimus carborundum me, me, me

                                        N Offline
                                        N Offline
                                        Nagy Vilmos
                                        wrote on last edited by
                                        #19

                                        I once worked on a system written in COBOL, an we had to loop through a madly dimensional array - what would today be a collection of collections:

                                        for each country
                                        for each sector
                                        for each segment
                                        for each stock
                                        for each date
                                        do the stuff
                                        loop
                                        loop
                                        loop
                                        loop
                                        loop

                                        All in one lovely single flat COBOL program. Actually, IIRC it was repeated, sometimes different ways round in lots of programs. I don't do COBOL no more.


                                        Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                                        1 Reply Last reply
                                        0
                                        • L Lost User

                                          Follow up on the Variable names thread below, I would like to ask what is the level of nested loops that is acceptable in general? Most people would agree that three levels is acceptable, but I would say stop at two. The third loops gets a bit messy.

                                          for(int i=0; i<100; i++) { //Okay
                                          for(int j=0; j<100; j++) { //Acceptable
                                          for(int k=0; k<100; k++) { //Messy
                                          }
                                          }
                                          }

                                          OriginalGriffO Offline
                                          OriginalGriffO Offline
                                          OriginalGriff
                                          wrote on last edited by
                                          #20

                                          Use as many as the algorithm requires. If you need to examine every single point in a three dimensional space, then trying to do it without nesting three deep is messy, inefficient, and wastefull.

                                          for (int x = 0; x < 100; x++)
                                          {
                                          for (int y = 0; y < 100; y++)
                                          {
                                          for (int z = 0; z < 100; z++)
                                          {
                                          ...
                                          }
                                          }
                                          }

                                          Worse, moving the nesting to methods to "make it look tidier" may well hide the amount of processing that is going on since it is no longer obvious that the single instruction in the middle of the centre loop is being executed 100 * 100 * 100 times, not just 100 times... Having a blanket rule "This is messy!" is wrong, and counter productive.

                                          Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

                                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                                          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups