For, While, and “Do… While” Loops

Programming can be pretty loopy sometimes, and there are a few different types of primary loops you will encounter. The two most common loops are “for” and “while”. There are a few different reasons why you would use a loop, and I think the most common reason is to work through an array index by index. Although, that really depends on what you’re doing because I’ve written games that handled all the logic in a while loop. Knowing when to choose a particular loop is very important, and it’s also important to choose the right one.

First things first, you should choose a “Do… While” loop when you need something to execute at least once. For example, you may need to capture user input. However, it is possible that you may need to capture more than one entry from the user. You can use a “Do… While” loop, or if that isn’t available in your chosen language trigger a while loop if necessary. While Loops are great when the end-case for the loop is not easily determined. On the flip side, if you have a well defined “n”-value or endpoint then you definitely want a “for” loop. Some higher level languages have a “For each” loop, which is just a simplified “for” loop targeted at arrays.

So just to recap: While loops are great when you can determine if a loop should stop based on something other than some predetermined value. If you have a predetermined value that you want the loop to end at then just use the for loop. Otherwise, you can run the risk of not ending while loop correctly and cause an infinite loop. If you’re careful with logic you can use the two loops interchangeably, but I would not recommend being that person.

Leave a comment

Your email address will not be published. Required fields are marked *