Getting Started with Programming – Part 3: Loops

Welcome to part 3 of this series where we introduce you to the very basics in programming. This time we’re going to look at loops, and as usual we will give you examples in both Arduino/C++ and Python.

The previous editions can be found here:

If you’re new to programming we recommend that you read those first.

[Wikipedia]

Why Loops?

In part 1 we briefly touched upon loops. Let’s repeat what we had to say back then:

Loops are parts of a code which in some matter will be repeated a certain amount of times (For loops) or until a condition changes (While loops). This doesn’t necessarily mean that the program is doing the exact same thing over and over again, but a certain chunk of the code will repeat while for example some variables change on each pass. These loops might sound a bit cryptic at first, but they are a completely necessary programming tool. For instance, in our temperature control system the whole main chunk of the code (all the logic that is represented by the flowchart) would have to be within a single while loop to be able to repeat an indefinite amount of times.”

In the red-ish text above from part 1 we mention a typical application for the while loop. The for loop are however used just as often:

The For Loop

As previously mentioned, this is a loop that repeats a certain amount of times. This tool is often used in conjunction with arrays (lists) and tables. We will not look at array-related examples in this part, however. We’ll save that for when we look at arrays specifically.

There are of course tons of other times you might want to use for loops. We will look at an example where we print out the n first numbers in the fibonacci sequence, where n is a number we will specifiy in the code.

Pseudocode

n is 42
fib_old is 0
fib_new is 1
fib_next is 1

FOR 0 to n:
	print fib_old
	
	fib_old is fib_new
	fib_new is fib_next
	fib_next is fib_new + fib_old

This code will first initalize the four variables at the top and then repeat the indented code n times, which in this case is 42. Let’s look at the more useful examples:

Arduino/C++

Serial.begin(115200);

int n = 42;
long fib_old = 0;
long fib_new = 1;
long fib_next = 1;

for(int i=0;i<n;i++){
	Serial.println(fib_old);
	
	fib_old = fib_new;
	fib_new = fib_next;
	fib_next = fib_new + fib_old;
}

Let’s start from the top.

The first line is an Arduino-specific function which is required to communicate over serial. We’ll talk about functions later.

Further down you’ll see a data type called long. These are like ints, but they can get larger before wrapping around. This is called overflowing. Overflowing is a concept we haven’t introduced yet (and this is not really related to the subject of this post), but an int is at least 16 bits large, while a long is at least 32 bits. If you’re at the maximum value alowed and add 1 to the variable, the result will become the negative extreme allowed or 0 (depends if the data type is signed or not). The reason for using int instead of long is mainly memory usage. Don’t use long if you don’t need to. In this example we use long since the numbers quickly become large, and we don’t want them to overflow.

Then we have the meat of the code which is the for loop. The for loop syntax is divided into three steps seperated by semicolons:

  1. int i=0 means that we initialize a counter called i which initially is 0. This counter can be, and often is used within the for loop, but this is not done in this example.
  2. i<n means that the for loop will run as long as i is smaller than n. This step of the syntax works as the condition in if statements which we talked about in part 2. If the condition is true the code within the loop is run. If not, the for loop ends for good. Since the counter starts at 0 the code is run exactly n times with this implementation.
  3. i++ is exactly the same as writing i=i+1 or i+=1. This step of the statement decides what the loop will do with the counter initialized in step 1 after each round. In our case we want to increment the counter by 1 each time, hence i++.

Serial.println() is another serial-related Arduino-specific function. In this case it prints the fib_old variable together with a line break at the end over serial.

Python

Now let’s do the same thing in Python!

n = 42
fib_old = 0
fib_new = 1
fib_next = 1

for i in range(0,n):
    print(fib_old)
    
    fib_old = fib_new
    fib_new = fib_next
    fib_next = fib_new + fib_old

As usual, the Python code is a bit tidier than the Arduino code.

In Python we don’t have to think about overflowing. The number limit is not restricted by variable type, but instead by the memory of your computer.

The for loop syntax is vastly different in Python compared to Arduino/C++. The i is the equivalent counter as in our previous example, which we in this case don’t use. But we need to have something there anyway. The counter is incremented by 1 each round implicitly. range(0,n) specifies how many times the loop will run. In this case it will run n times.

print(fib_old) prints the variable print_old to the terminal togheter with a line break.

The While Loop

This loop is closely related to the for loop. You can implement every for loop as a while loop. However, you should use for loops where it makes sense since it is a lot tidier.

The while loop is also closely related to the if statement. It basically only checks if a condition is true, and if it is it runs the loop (just like step 2 in the Arduino/C++-implementation of the for loop).

The while loop is useful in less predictable scenarios where you don’t know how many times it will run. For instance if you want a loop to run until you get an input from a sensor. For demonstration purposes, however, we’ll do exactly the same as in the previous examples using while loops instead of for loops.

Pseudocode

n is 42
fib_old is 0
fib_new is 1
fib_next is 1
i is 0

While i<n:
	print fib_old
	
	fib_old is fib_new
	fib_new is fib_next
	fib_next is fib_new + fib_old
	
	i++

As you can see we introduce a new variable at the top that we call i. We use this as a counter. This works exactly as the is we used in the previous examples since we at the bottom of the loop increment it by one.

Arduino/C++

Serial.begin(115200);

int n = 42;
long fib_old = 0;
long fib_new = 1;
long fib_next = 1;
int i = 0;

while(i<n){
	Serial.println(fib_old);
	
	fib_old = fib_new;
	fib_new = fib_next;
	fib_next = fib_new + fib_old;
	
	i++;
}

This implementation shouldn’t really surprise you at this point. Notice how we just extract step 1 and 3 and move them above and at the bottom of the loop, respectively, while keeping step 2.

Python

n = 42
fib_old = 0
fib_new = 1
fib_next = 1
i = 0

while i<n:
    print(fib_old)
    
    fib_old = fib_new
    fib_new = fib_next
    fib_next = fib_new + fib_old
    
    i += 1

Python’s while loop syntax is more similar to Arduino/C++’s than the for loop. Python doesn’t support i++ so we need to use the i += 1 syntax instead.

While(1)

When we want something to repeat indefinitely we use while(1). This makes it impossible to exit the loop without killing the program or shutting down the power since the condition 1 always is true. This is often used in embedded systems when writing firmware on microcontrollers. On the Arduino the void loop()-function is the same as a while(1) loop.

If you change the python code above from while i<n to while 1 you’re gonna have a bad time since the program quickly will eat up all your memory.

Summary

Loops are super useful, powerful and completely necessary tools in programming. They are a lot more flexible and handy that you might get the impression of after reading this post, but the purpose of this series is to just give you an introduction to programming and not go super in-depth.

We still have a lot to cover, so stay tuned!

Continue our series by reading part 4 where we talk about arrays and lists!

Related Posts

Menu