Iterative Loops: While Loops

    Iterative Loops: While Loops

      Shmoop isn't a big fan of doing dishes. It's all fun and games when they're holding a big helping of pad kee mao, but once all the rice noodles have been slurped and all the broccoli's been crunched, we're left with a soy sauce-stained plate that, let's face it, won't get washed until all the counters and the sink are too cluttered with dishes to stack any more.

      Besides reminding us of the pain that is doing basic chores, dishes are a great example of the power of loops. To loop through the dishes, there are two options. The first option's creating a for loop and spending the time to count the number of plates, bowls, cups, silverware, and strawberry stem removers that need to be washed so we know the exact moment the loop needs to stop. Sure, this method works, but think of all the time lost counting every single grapefruit spoon on that mountain of dishes. It would take less time just to wash the dishes ourselves.

      Instead, we could go with the second option: run a loop for an unspecified amount of time. Just wait until all of the dirty dishes have been washed and then stop. Since we wouldn't need an exact count (just an end condition instead), the implementation of said vague loop is called a while loop. In pseudocode, a dish-washing while loop would look something like this:

      WHILE length(dirtyDishes) NOT 0:
      	currentDish = remove(dirtyDishes[0])
      	wash(currentDish)
      END WHILE

      We're taking a couple of jumps here, so bear with us for a minute. dirtyDishes is the list with all the…dirty dishes. remove() takes a dish from the list, which is then assigned to currentDish. After that, currentDish is sent through a wash() function. We'll just assume that all the functions work for the sake of the example.

      If all the functions work (and we just assumed they would), then this loop's going to run as long as its condition that there are still dirty dishes in the list is true. The minute dirtyDishes has a length of 0, the while loop ends.

      Now that the dishes are washing themselves, we could also make a loop to fill the pet food bowl with a list cleverly named petFood.

      WHILE length(petFood) NOT 100:
      	fillFood(petFood)
      END WHILE

      Don't worry about the fillFood() function. The only thing that matters is that while the amount of unspecified pet food isn't 100, this loop's going to keep going.

      While Loops in the Wild

      While loops don't just simulate our chores, though. They're especially good at keeping some process or program running until it's finished or the user decides to quit/exit.

      For example, if we made a video game and wanted to keep it running until the user hits 'q' to quit, we could program an outer while loop around the primary game code that looks something like the following (except, you know…in a language).

      input = userInput()
      WHILE userInput NOT 'q':
      	runGame()
      END WHILE

      As long as the user doesn't hit the 'q' character, the game will continue on its merry way. Forever.

      And here we run into the big, glaring problem with loops of any kind: if the quit or end condition never happens, the loop's just going to continue forever. While loops are exactly like for loops in that: if the condition for ending the loop can never happen, it's game over…which is to say, it's going to keep running forever. That means a stack overflow and possibly the computer crashing.

      Hey, it happens. Just recode and try again.

      While loops are also useful to help search for elements in a list. Set up your loop to run as long as the element in the list isn't equal to the one you want…and you haven't searched all the way through the list yet. (That last bit's surprisingly helpful for not getting errors for trying to search for something in an index that doesn't exist. Just throwing that out there.)

      Let's say we wanted to search a user-defined word for the letter 'e'. Many words (read: most) have at least one 'e', so this loop should usually quit before we get to the end of the word.

      Just to make sure our program quits, even if there isn't an 'e' in the word, the code should also check to make sure it isn't trying to access a character beyond the length of the word. If the loop either finds the letter 'e' or runs out of space in the word, it'll quit the loop.

      wordLength = length(theWord)
      index = 0
      WHILE index LESS THAN wordLength: 
      	IF theWord[index] EQUALS 'e':
      		BREAK from loop
      	END IF
      END WHILE

      Yep, we're treating theWord like a list in this situation (and that's going to change depending on the language. Python will be super okay with this syntax, but Java's going to make you use a method called charAt()). There are two points that break the loop: index being greater than or equal to the length of theWord, and when theWord[index] equals 'e'. If at any point the value of that character is 'e', the loop's going to break, making it end prematurely.

      It isn't a part of the official condition, but it does act as a condition when that conditional's true. You'd be surprised how helpful a well-placed break can be.

      Do-While Loops

      One more version of a while loop. While loops proper only run if the starting condition's true on the first iteration. Sometimes the loop needs to run at least once—even if the condition's never true. Even if you immediately quit a program after starting it, the menu should appear at least once. In cases like these, we can use a modified form of a while loop, called a do-while loop. Do-while loops run the loop once before testing the condition. For this reason, the test conditions in do-while loops are the last part of the loop, showing that the code block runs before the condition does.

      A do-while loop for blowing out candles on a birthday cake would look something like the following.

      DO:
      	blowOutCandle()
      WHILE (litCandles)
      END WHILE

      Since 0th birthdays aren't typically celebrated with cake/candles like other birthdays, we can safely assume that there's going to be at least one candle on the cake to blow out (meaning that the loop should always run at least once).

      But enough talk. Cake time.

      (Source)