Fundamentals of Programming: Part 7 – Loops

by
Inf

Welcome to Part 7: Loops! I hope you have enjoyed the previous parts and if you haven’t checked them yet, you should! Here’s a link to Part 1!

In this part, we consider another fundamental building blocks of programs: Loops. What are they? Simply, a method for telling your computer to do the same thing a bunch of times. Nothing too hard huh? Let’s get on with it!

As I said, a loop is a cycle, where the ending point is also the starting point. I.e. when you reach the end, you actually find yourself at the start.

A loop in programming is pretty much the same: You tell your computer execute a set of instructions for a number of times or until some condition is met. Then stop repeating and proceed with other stuff.

Say you want to write a program that models a bunny. The bunny only knows how to jump. Now, you want that bunny to jump 5 times. How would you do that?

You can write it like this:

Jump
Jump
Jump
Jump
Jump

That is, you write your instructions 5 times. If you want 10 jumps, you write 10 jump instructions. If you want 100 jumps, you write 100 jumps instructions. If you want 10,000? Ugh… You see the problem? You don’t want to have to write that instruction 10,000 times! And that’s why you’d use a loop. Wouldn’t it be nice to just tell the program “do this 10,000 times”? Something like:

do 10,000 times{
	jump
}

That would be nice huh? Well, you just wrote a loop! It’s not exactly written like above, but the true ways of writing loops look just like that.

There are 3 main ways of writing loops, and we’ll go through each of them in turn, and I’ll tell you when to use them.

For Loop

The first way, but probably the weirdest way of writing a loop is the For loop. Sorry, but it really doesn’t look like the loop above! The other kinds of loops do look friendlier though! If I want to write that loop above as a For loop:

for (int i = 0; i < 10000; i++){
    jump
}

WHAT IS THAT THING?!! It’s so hard to read! Lol… no it isn’t. Wait, we’ll go through it in parts.

“for” is perhaps the easiest thing to read. It’s a keyword indicating a For loop and in the end, you will come to just read it as “for 10,000 times”.

(int i = 0; i < 10000; i++) ouch… But hey, do you see this consists of 3 parts? Let’s break it down, it’s not that hard!

int i = 0; We are just saying, initialize variable i as an Integer, and set its value as zero to begin with. This is done only ONCE in the loop, i.e. the start!

i < 10000; If you have read the part on Conditions, this is familiar to you now. It’s just a check to see if the value of i is LESS than 10000. This check is performed at EVERY RUN of the loop. Hence, we’ll check the value of i 10,000 times during execution.

i++ that’s new! It’s the short form of “i = i + 1”, i.e. add 1 to the current value of i. The incrementing is done ONCE every run, so we increment the value of i 10,001 times! What? Yep, 10,001 times! Remember, 0 to 9999 is 10,000 times! But see, the loop stops at 10,000 times right, so the value of i has to become 10,000 at some point. 0 to 10,000 is? 10,001!

So if we read the whole thing now:

for (int i = 0; i < 10000; i++) means, "do the following instructions for 10,000 times". The variable i is what we call a loop counter. It keeps track of how many times we have executed the loop so far, i.e. how many times we have run our instructions in a loop. The loop counter acts as our memory, so we remember how many times we’ve done that loop.

Why do we need 3 parts? We need a starting point (i = 0). We also need to know when to stop (i < 10000). Finally, we need to update our count of how many times we’ve run so far (i++). With those 3 elements together, we’re able to know where we start, how many times we looped and when we stop.

We start counting at zero and every time the loop executes, we increment the value of i (i++) once. We continue running the loop until i is no longer less than 10,000 i.e. i = 10,000 stops the loop. After those checks and whatnot, our bunny jumps! Then we restart, check the value of i, increment it, bunny jumps, check value of i, increments it, bunny jumps etc… until 10,000.

While Loop

So that was one way of doing looping. We can also use a While loop. This one looks simpler, but beware, it has a trap!

while (i < 10000){
    jump
}

As before, “while” is a keyword indicating that a loop should be done.

(i < 10000) is a check, so we know when to stop. So we read "while i is less than 10,000, do these instructions" Have you noticed the trap yet? It may not be that obvious, so compare with the For loop above. Tip: i++ The incrementing of the counter i is missing! What happens if you do that? You have a bunny that never stops jumping! An infinite loop! Since you're never incrementing the value of i, the check will always return true since every time we compare, i is still zero. The loop never stops and in the end, you have a very tired bunny. You have to be really careful about not missing the incrementer if you're using While loops. If you're not counting, or doing some other kind of check, you need to make sure there's a stopping condition for the loop. Otherwise, you will in most cases, have a non-responding program to deal with while it's stuck in the loop. Infinite loops do have their uses though. For example, you can keep repeating your program to read an unknown number of inputs from the user, until they enter "quit" for example. Since you don't know when to stop, you just run infinite number of times and implement a manual stop condition. We'll see about that in the ending section of this part! Here's a correctly written While loop that behaves as we expect: [plain] int i = 0 while (i < 10000){ jump i++ } [/plain] But why do you ever need a While loop? A For loop works perfectly well for this task! It happens that you're performing actions that don't rely on a counter. Or you don't really know when you have to stop. A For loop runs for a finite number of times. A While loop can run for as long as you want it to, maybe depending on some external condition or some user action. Here’s an example:

while ( isUserPresent() ){
    jump
}

In this loop, we’re using a function isUserPresent. You can ignore it for now. Just know that it’ll return true if the user is currently sitting at their desk. It returns false if the user is not present. Functions come in the next part.

This loop will have our bunny jump if the user is there to see it. If the user leaves, the check becomes “false” and the loop stops. The bunny then stops jumping and the loop ends.

As you can see, this While loop depends on an external condition that’s not related to counting. You don’t know for how long the user will be at their desk and so in effect, you’re executing the loop until the user leaves, potentially executing an infinite number of times (user never leaves). You can’t easily do this with a For loop, since it’s finite.

A While loop gives you more flexibility to control when to start, how many times to execute and when to stop. Or if you wish, you can continue as long as you want (infinite loop).

Do While Loop

A third way of writing loops is the Do While loop, also called Repeat Until loop. This is not present in all languages, but can be quite useful in some conditions. Let’s compare with a While loop.

int i = 10000
while (i < 10000){
    jump
    i++
}

What happens in this case? Check the initial value of i (10,000)? while (i < 10000) never executes because i is NOT less than 10,000. It is EQUAL to 10,000! So your loop never runs! There are cases when you want the loop to run at least once before the check is made. Say for example, you want the bunny to jump at least once, even if there may not be any user. You would not be able to do this with the While loop without extensive checking and tricking the program. But you can very easily do this with a Do While loop: [plain] do{ jump }while (isUserPresent()); [/plain] Note how we shifted the check AFTER the instructions. So no matter what, we'll still execute the "jump" instruction at least once before we reach the first check for user presence. This kind of loop is less frequently used as compared to the above two, but am including it just so you know it exists. One realistic scenario where you might want to use a Do While loop is to check that the user's input is what you expect, and if it's not, keep asking for an input until you get what you want. Here is a non-language-specific example: [plain] do{ Output "Say Y or N: " Get user input }while (input != "Y" || input != "N"); [/plain] I chose to give a non-language-specific example to keep it as simple as possible. This block of code will execute at least once and ask the user to either type "Y" or "N". We then read what the user typed. Finally, we check if the input was either "Y" or "N". If the value input was neither of these, we basically drop into an infinite loop until we get what we want. That is, we keep asking the user until they say either "Y" or "N" and then stop the loop. This illustrates an example of where you need to get the input first, then decide what to do. You could have used a While loop too: [plain] Output "Say Y or N: " Get user input while (input != "Y" || input != "N"){ Output "Say Y or N: " read input } [/plain] Notice how you're repeating the instructions? That's something you want to avoid in programming. Stick to the Don't Repeat Yourself (DRY) principle in programming. The Do While is a simpler alternative here.

Break and Continue

Before we end, there are two important keywords that you need to know. If you read Part 6 on Conditions, you’ve already seen “break” used inside a Switch block.

“break” tells your program to “break out” of the structure it current is in. It’s mainly used in loops, where you want to manually stop the loop, especially if you’re using an infinite loop and want to manually stop at some point.

“continue” tells your loop to ignore the rest of the instructions in the loop and restart with the next cycle of the loop.

Let’s see examples of these keywords:

int i = 1
while (true){

    jump
    i++

    if (i == 10000){
        break
    }

}

The loop above is a complex way of just stopping when i is 10,000. We’re using an infinite While loop. Notice while (true)? Well, the check will always return true since we’re saying it’s “true”! There is no stopping condition there. Instead, we use an If condition to do the check, and “break” the loop when we want. So when i reaches 10,000, we break out of the loop and stop it. Fairly stupid way to do it, but it’s just to illustrate “break”.

do{
    output "Say Y or N: "
    read input

    if (input == "N"){
        continue
    }

    output "Hello!"
}while(true);

The loop above is again, an infinite loop. We want the user to type “Y” or “N”. If they type “N”, we don’t greet them since “continue” is activated and the loop restarts, skipping the output line. If they say “Y”, the If condition doesn’t trigger and we say “Hello!” to them.

P.s. Normally, you don’t compare Strings like that. You don’t do input == “N” for e.g. but would use some function. We’ll see about that later.

That’s all for this part on loops. Remember, they just allow you to tell the computer to do a set of actions multiple times. There are multiple ways of writing them, and you’ll use different ways depending on what you want to achieve. For finite loops where you know how many times you want to execute, use For. For more flexibility, use While. If you want to run at least once before checking, use Do While.

I hope you found this part interesting. If you have questions, please ask in the comments section below. Suggestions welcome!

[seriesposts title=”In the same series:” titletag=”h3″ listtype=ul show_date=0]