Iterative Loops: How Does it Work?

    Iterative Loops: How Does it Work?

      Lather, rinse, repeat. Pretty common turn of phrase, no? If you look hard enough, you'll even find computer scientists joking around about rinsing and repeating.

      Thing is, computer scientists love loops and those instructions that seem to show up on every single bottle of shampoo without any other explanation are simple, popular, and inherently mockable. Plus, they're the perfect example of an infinite, iterative loop. If you follow these instructions, you'll repeat all the steps over and over again until either you give up or the shampoo bottle runs out.

      (We bet shampoo companies are betting on the second option. Just sayin'.)

      Loops repeat: that's their problem-solving paradigm. When you use a loop, you're doing so to take a larger problem and divide it into a bunch of smaller sub-problems. In computer science, this problem-solving can take the form of

      • calculating the size of a list.
      • adding up all the elements inside said list.
      • running a program or function until some return value's reached.
      • printing out a word or phrase a certain number of times. 
      • pretty much any other task that can be seen as a bunch of repeatable steps.

      Iterative looping isn't a concept exclusive to computer science. Conquering that advanced flamenco final exam all at once isn't going to work out too well. Instead, try practicing one move at a time, perfectly, until the routine's complete.

      Once the routine's put together, run it over and over until you dream to castanet rhythms. In the same way, you can't (or should we say shouldn't) write the entirety of a 20-page essay on the history of postmodern horticulture in one night. If you schedule well, you can write a page or two a night for a few weeks, then spend the last couple of days running through the paper to perfect the details.

      So much easier.

      Loops are no different. In fact, we'd even say they're better than that fancy footwork or that intense research paper because once the loop's set up, you don't have to do any more work to keep it going. The loop will just keep going, completing whatever you need it to until it's told to stop.

      The trick? A poorly-designed loop is never going to stop. These loops can quickly turn from trusted helper to terrifying monstrosity in just a few lines of code. We're talking "Sorcerer's Apprentice," infinite broom-splitting levels of terror. It's up to you, the creator of the loop, to make sure nothing bad like that ever takes place. Take care of your loops and your loops'll take care of you. We promise.

      Unless an unruly apprentice comes along and messes it up, of course.