Iterative Loops: Applications of For Loops
Iterative Loops: Applications of For Loops
Loops have tons of applications, but most of the time they have boundaries. Think about a really good pop song. The lyrics are catchy, the beat's sick, but there are only so many times you can hear the chorus before that cute little trumpet riff starts to sound less cool and interesting and more like a very loud, brassy mosquito.
Musicians know this. Really well.
That's why, after about three or four repetitions of the chorus, the song ends. It has a planned, determined stopping point, unlike your brain when you just get the chorus stuck in your head and it keeps playing over and over until you just wish that song had never been born.
Say what you will about for loops, but just like most songs (with a couple exceptions), it knows when to stop. Sometimes that fact isn't helpful at all, but other times it's a code-saver.
For-Each Loops
When it comes to lists, for loops are the best. Say you have a list with n elements. To perform some operation on every element, all you need to do is write a loop that starts at 0, ends at n, and has the operation inside the loop. Just like that, you're done.
Example time? Example time. Let's say we have a list like this one:
theList = {3, 7, 9, 4, 1, 0}
Adding up all the elements in this list with a for loop would look something like the following pseudocode.
sum = 0 for n FROM 0 TO length(theList): sum = sum + theList[n]
length()
is a function that finds the length of the list. We're also making the assumption that indexing in the language starts at 0—not 1. Depending on the programming language, the syntax is going to change, but you get the idea. This code walks down the list using the for loop, adding each element to sum
, one after the other. Once, it's done, sum
will equal 24.
Finding the minimum value of this list is just as easy.
min = theList[0] for element IN theList: IF element < min: min = element END IF END FOR
In the above pseudocode, min
is set to 3 (since that's theList[0]
) before the loop even runs. Since we already set min
to equal to theList[0]
, we don't technically need to compare the two anymore, but that optimization is so miniscule that we won't even worry about it. After the loop runs through the first five elements, it's going to change min
to 1 (since 1 is less than 3, last we checked). During the final iteration, min
becomes 0: the smallest value in the list.
Take another look at that minimum-finding loop. Working with lists and for loops is such a common task that many languages have a special syntax just for looping through lists. Instead of using an explicit counter (like n
), the loop will just go through every element in a list one by one and do something with that element. When all of the elements have been processed, this for-each loop quits automatically.
Notice how the first step is to set the starting minimum to the first element of the list? We can't stress just how important that step is in finding a minimum value. Always, always, always make the starting minimum or maximum an actual value. Otherwise, you could set it to some ridiculous value that ends up being the max or min without ever being in the list.
Rant: over.
Could this type of loop lose some efficiency by going through every element when it might only need to go through everything except the first element? Maybe. In the grand scheme of things, though, that lost efficiency isn't going to matter nearly as much as having a loop that updates itself in case the list grows or shrinks on its own without you needing to worry about it. Plus, it's much more readable when you're working with lists in particular.
Fizz Buzz: The Tech Interview's Worst-Kept Secret
If you made it through elementary school (and, uh…we're guessing you did since you're reading and all), you've probably played your fair share of 'rithmatic-style games. Our personal favorite was Fizz Buzz—and we're pretty sure it's the favorite of most tech companies, since it keeps showing up in coding interviews.
Here are the basic rules.
- Start counting numbers, starting from 1.
- Whenever the next number's a multiple of 3 (3, 6, 9,…), replace the actual number with, "Fizz."
- Whenever the next number's a multiple of 5, replace it with the word, "Buzz."
- Whenever the number's a multiple of both 3 and 5, say, "Fizz Buzz."
- Keep going until someone messes up.
If you were to start at 1 and go to 15, the sequence would look something like this, assuming no one messes up:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizz Buzz.
As fun as this is to play, programming the solution is a surprisingly fun brainteaser (said every tech company ever). The trick with coding this game is to not overthink things. We know, we know, the set-up of the game sounds like there's some elegant solution with well-placed conditionals, but…there isn't.
Trust us.
If we were to program Fizz Buzz, to print out the results of running through the numbers 1 – 100, our pseudocode would look like the following.
FOR counter FROM 1 TO 100: IF counter % 3 EQUALS 0 AND counter % 5 EQUALS 0: PRINT "Fizz Buzz, " ELSE IF counter % 5 EQUALS 0: PRINT "Buzz" ELSE IF counter % 3 EQUALS 0: PRINT "Fizz" ELSE: PRINT counter END IF END FOR
(That percentage sign is the mod operator; it tells you the remainder of dividing one positive number from another. If you take any n mod m and get 0, you know that n is divisible by m.)
The first condition checks if counter
is divisible by both 3 and 5. The second and third conditions check if counter
is divisible by 5 or 3. If all three checks fail, it finally just prints out the number. This program's first 15 lines of output would be the following.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz
Believe it or not, this is the basic map for the solution—no matter the language. Many programmers think it's more elegant to set counter % 3 EQUALS 0
and counter % 5 EQUALS 0
to boolean variables so that you don't need to repeat the same code (source), but the end result will have the same structure as far as the conditionals are concerned.
You can try to be more clever with the conditional structure (maybe nesting counter % 5
inside of counter % 3
), but it's only going to make the code look messy and unorganized. Try it out for yourself if you don't believe us.
(Source)