Iterative Loops: For Loops
Iterative Loops: For Loops
Shmoop loves running…if you stretch the definition of "running" to laying on the couch, breaking out a bag of Red Vines, and debating the philosophical meaning behind Hop on Pop.
Counts, right?
Back before we decided to replace actual calisthenics with brain calisthenics, Shmoop went to gym class just like everyone else. Our teacher would give us a number of times we had to repeat an exercise like push-ups or laps around the gym. Then, once we'd done so many laps or hurdles or stretches or whatever, it was time to move on to the next set of exercises.
We still have nightmares.
For loops are pretty much the code equivalent of our high school gym teacher. Use them whenever you know about how many times some task should be done in order to solve the problem. With push-ups, we're willing to bet you (or your PE teacher) use some sort of counter to keep track of your exercises—specifically, how many you've already done. For loops are no different: they use counters to keep track of how many times the loop's run vs. how many times it needs to run before it can end.
This counter is usually initialized at some value, like 0 or 1, and has a value added to it every time the block of code runs. Once the counter reaches some predetermined value—say, 5—the loop's going to end. In most cases, counters are either added to or subtracted from. Whether you count from 0 to x or backwards from x to 0 is mostly a result of opinion and the particular job of the loop. Do you want to count how many iterations the loop's gone through or how many it has left?
A basic for loop looks something like this:
FOR counter FROM 0 TO 5: PRINT "What's shakin', bacon?" counter = counter + 1 END FOR
In particular, this loop will print out What's shakin', bacon?
five times, each on a new line:
What's shakin', bacon? What's shakin', bacon? What's shakin', bacon? What's shakin', bacon? What's shakin', bacon?
Whatever language you're working in (which isn't this; it's pseudocode), if it has a for loop, the syntax is going to be some flavor of these basic components.
The first time the loop runs, the code assigns counter
to the value 0. The loop runs through once, running the print statement, and counter
goes up to 1. Then the loop runs again, sending the counter to 2. Then 3. And 4. When the counter equals 5, the loop quits before running the print line again because that's the end of the counter's range.
You might notice that, despite stopping before running the code when counter
equals 5, the result still has five printed lines. For the sake of consistency, we're going to continue running loops by including the bottom end of the range but excluding the top end for exactly that reason.
That's where languages tend to differ syntactically: some give more leeway on what should be included in the range of counter
(hello, C and Java). Some automatically include the numbers at both ends (oh hey, R). Others only let you include the bottom number and exclude the top number (looking at you, Python).
Different languages will also change where the incrementation of counter
goes. It could be in the same line as the initialization of counter
and its end condition, it could be inside the loop, or it could be hidden away from view altogether. Check with your particular syntax to figure out where all the parts go.
Manipulating counter
Want to change the number of times that "What's shakin', bacon?" prints? You've got some options. Maybe not as many options as you would have at a The Fast and Furious movie festival, but definitely more options than you would have at a The Fast and Furious sequel-naming meeting. (Let's face it: all the possible combinations of "fast," "furious," and the number of the sequel have been uncovered at this point.)
Instead of increasing the value of code
, you could totally decrease the value of counter
at every definition. It doesn't even need to be a positive number, actually.
FOR counter FROM -3 TO 5: PRINT "What's crackin', Patton?" counter = counter + 1 END FOR
Now the message, a clever homage to our favorite outspoken advocate for military tanks, is going to print out eight times—the number of values between -3 and 5.
To go down instead of up, we could write something like the following pseudocode.
FOR counter FROM 10 TO 5: PRINT "What's up, paper cup?" counter = counter - 1 END FOR
Be careful with this formula, though, since it's the easiest way to make a loop run infinitely. We're just throwing that out there
Two more changes before we go. Most languages will let you change counter by any value—not just 1.
FOR counter FROM 0 TO 7: PRINT "What's the news, Santa Cruz?" counter = counter + 2 END FOR
Now counter
is incremented by two every time the loop iterates. Since counter
now goes from 0 to 2 to 4 to 6, the loop will only run three times instead of 5.
Aaaaand, last one.
FOR counter FROM 0 TO 5: PRINT "What's the time, mountain climb?" counter = counter – 1 END FOR
Oof. There's a bigger issue here than that bizarre print statement about hiking. Computer scientists aren't exactly soothsayers, but they can usually see where code might loop infinitely and spiral out of control. counter
starts at 0 like plenty of the other loops, but it now decrements at every iteration instead of incrementing, going down by one every time. Since it's decreasing from 0, counter
will always be smaller than 5, making the loop solidly ready to never end.
Maybe it's a statement about Mount Everest's climbability?