Secret Code

Arrays and Loops

Oliver Higgins

Issue 3, September 2017

Last month we looked at data types with variables. But what if we have a group of values that we want to store? That’s what arrays are for.

As we progress in programming, we are quickly presented with the daunting task of repetition and how to deal with it. After all, this is what computers are good at. In this article, we will discuss loops and arrays. Working with both of these we can automate many tedious and complicated tasks. So what comes first? The loop or the array? Depending on the loop, you need an array, and the best way to go through an array is with a loop - so the answer is both, concurrently. However, due to the our human inability to multi-task and read two columns at the same time, we will look at arrays first. We would recommend reading this article then re-reading it again, as the two subjects are intertwined.

To quickly recap, a variable is something we need to monitor and change. We define the variable and allocate data to go into it. This is then read by the computer and changed as the program progresses. Say, for example, we want to create a program that calculates two numbers. When we calculate two numbers, we allocate a container for the number, called A, and a container for our other number and call it B. The user enters data into the calculator. The calculator then gets the number from the A variable, performs the required math with B variable, and then returns the result. We now have a third number that we can output to the user. However, once your program becomes more complex, you will find that you will have similar types of data, or a lot of data that relates to the same information; in which case, defining an individual variable each time you need one, isn’t the best approach.

If we look back on a variable being a container that we can store items in, the array is a collection, group or list of those containers. For example, we can have six objects that are the same containers but hold different colours [1]. The array gives us the opportunity to simply tell the code which index our item is located in, and it will return that very item.


Here we have declared a series of six integer variables, which gives us six containers to use to store our information.

int x0 = 0 
int x1 = 0 
int x2 = 0 
int x3 = 0 
int x4 = 0 
int x5 = 0

However, we have to write it, access it, and every time we need to make a change it must be rewritten again, which becomes a very laborious task and one prone to user errors. What happens if there are 6 or 7 or 389,034 integers? It is impossible to maintain the code and also, you may not know how many variables we’ll need until runtime. What if it’s dynamic and the number needed changes? We want to be able to create a list of variables that we can move through, which are as big or small as we need. This is where the array comes in. If we are to look at our previous declarations on the six integers, we can do it much more efficiently using the following:

int x[6]  // this will give us six elements, but remember the count starts at 0 and goes to 5

Let’s take a closer look at this declaration. The first part is “int”. We are declaring a variable of type integer. Remember that all elements of the array must be of the same type; we cannot store a number in one element and a string in another. The next is the variable name, in this case, “x”. Finally, we have square brackets with a number in it. To access the element we simply specify the elements number that we need. For example, to read back the information in the first element we use:


This will give us the first element in the array. Remember, programmers start counting at 0, not 1. To access any element, we require, we just change the number:


This will give us the fourth element in the array. Now at this point, you will be forgiven for asking, “what difference does that have to the original set of variables we made?”. We still have to write down which one we want to access; so you are right, kind of; this is the segue we need to look at loops.

What if we could tell the system that we wanted it to do the same thing over and over again? How do we inform the system of what we need to be done, and how does it know where it is up to? This is the marriage between arrays and loops. For example, let’s say we have a class of 15 students and we need to store their final grades. We will be using the whole number, so we need to declare an array of integers to do this.

My partner said, “Please go to the store and buy a carton of milk, and if they have eggs, get six.” I came back with six cartons of milk, they said, “why on Earth did you buy six cartons of milk?”

“They had eggs.”

comic one

The joke here is the implication that "get six" applies to eggs. As a human we pick up on this nuance. However a computer sees this instruction as "buy 1 carton of milk. if the store has eggs, buy six cartons of milk". There is no direct request to purchase eggs made at all. This is one of the key considerations to make when programming. Computers don't think like humans.

int studentGrade[15]; // This will give us an array of integers to store our student grades in. 

With the above array, we can access any number by just calling the index. We will digress here to discuss loops before bring them both together at the end of the article.

While we have done our best to be as “pseudo code” as possible, the above code is very “C” syntax specific. This is because there are some differences here when it comes to using languages, such as Arduino/C and Python3. In Python, an array is referred to as a list. As with other variables in Python, we do not need to specify the type of the variable, but when using a list, not all elements must be of the same type. You can mix in integers with strings and other data types.


shopping = ["potato",  "tomato", 9.99, 4.67] 
list1 = ["a", "b", "c", "d"] 
list2 = [1, 2, 3, 4, 5 ];

However when we access an element with the array, it is very similar:

>>> shopping = ["potato",  "tomato", 9.99, 4.67] 
>>> print (shopping[1]) 

Before we finish arrays and move on to loops, we need to show just how useful both can be when combined. The below code will produce the same output for Arduino/C and in Python3. You can see we have created our array in one line in the Arduino code, compared to our original declarations. Both sets of code declare the three elements of the shoppingList array, which contains three items that are strings.


Put potatoes, tomatoes and beans onto my shopping list then
Go to the shop. 
Get list out of pocket, 
Starting at the top, we read each item and go looking for it.


char* shoppingList[]={"potatoes", "tomatoes", "beans"}; 
void setup(){ 

void loop(){ 
for (int i = 0; i < 3; i++){ 
   Serial.print("Current item : "); 


shoppingList = ["potatoes", "tomatoes",  "beans"] 
for item in shoppingList:         
    print ("Current item :", item) 


Loops are fundamental to making your coding life that much better. We have three main loops that we use when we need the system to do repetitive tasks. The For loop, the Do loop (or Do While), and the While loop.


The For Loop

We use this when we have a required number of loops to complete, and we “know” how many times we need it to execute in order to achieve our task. This is probably one of the most commonly used loops and is extremely versatile. In the context of the array, we know how many elements that are in it, through either the original declarations or by accessing the number of elements.

int size=sizeof(arr) 

The basic anatomy of a For loop is:

for x = 0 to 5{ 
     do something each time 
// Loop back to the beginning and increment x. When x reaches 5, the loop will finish, and the code will continue to execute.
for (initialisation; condition; iteration) {  
     statement 1; 
     statement 2; 

The above code is a more robust example.

Variable initialisation is the initialisation of the counter of the loop. This is the declaration and instantiation of the varible that we will use in the loop.

Condition is any logical condition that controls the number of times the loop statements are executed. How many times do you want to do this loop? Of course, it is capable of a lot more than this, but we are using this example in the interest of keeping things simple.

Iteration/increment is the increment/decrement of the counter. When the loop finishes, does the counter count up or count down?

Finally, this is some code you can run to test in Arduino/C/Processing. This loop will increment 100 times and print each loop:

//Arduino code 
for(int x=0; x<100; x++){ 

The below code will create and fill the student array we used before, then use a For loop to access the student array:

// Arduino code 
int studentGrade[4]; // This will give us an array of integers to store grades in. 
int i; 
void setup() { 
  // Enter the student grades here. Note we 
  // declared an array of 4. 
  // To access the array we use 0-3 
  studentGrade[0] = 81; 
  studentGrade[1] = 76; 
  studentGrade[2] = 84; 
  studentGrade[3] = 95; 

void loop() { 
  for (i = 0; i < 4; i++) { 
    Serial.print(": "); 


This example comes from the Arduino guide on For loops, and is a great example of a real-world application.

Note: you will need to connect an LED to pin 10 as PWM is not available on the in-built LED.

// Arduino code LED Dimmer 
int PWMpin = 10; // LED in series with 470 ohm 
     // resistor on pin 10 
void setup() { 
  // no setup needed 

void loop() { 
   for (int i=0; i <= 255; i++){ 
      analogWrite(PWMpin, i); 


The Do While Loop

The Do While loop allows execution of statements inside the block of the loop, for at least one time, even if the condition in the loop fails.

In simple English, we ask the system to “do” something “while” something else is happening. We “do” it first, then we check if the variable meets the criteria for the “while”, and repeat or terminate accordingly. Basic syntax to use the Do While loop is:

variable initialisation; 
do { 
    statement 1; 
    statement 2; 
    iteration of variable; 
} while (condition)  

Variable initialisation is the initialisation of the counter of the loop, before the start of the Do While loop. Condition is any logical condition that controls the number of times the loop statements are executed. Note: Iteration/increment is the increment/decrement of the counter.

A programmer goes out to get some dry cleaning. His partner told him, “While you’re out, pick up some milk.”

He never came home.

comic two

In code terms, the instruction is "while you're out, get some milk". It doesn't say "while you're out, grab a carton of milk and come home". While the "come home" instruction is implied for a human, a computer would not pick up on this assumption. Since it's then always "out", it would continue to pick up more and more milk.


The While Loop

This is another loop like the Do While loop, in C. The While loop allows execution of statements inside block of loop only if condition in loop succeeds. Please note that compared to the Do While loop the condition check here occurs BEFORE the execution of the code. This way you may check the conditions and avoid executing code at

variable initialisation; 
do { 
while (condition) { 
    statement 1; 
    statement 2; 
    iteration of variable; 

all if required. Note: Iteration/increment is the increment/decrement of the counter.


These three loops will provide the bulk of the pragmatical iterations you will need. However, if something does not meet your needs, you can always nest loops. So your loops can have loops, which can have loops!

BREAKS: Loops have controls structures within them, and the most common are called breaks. The break is used when you need to suddenly terminate the loop, mid-loop, and return to program flow. How does this differ from the While and the Do While loops? The simplest answer would be exceptions. The code may execute intention as described using your loop, but there may be a situation where the system has an interrupt or emergency protocol. Your loop may check this with an If statement, and then break the loop mid-execution to limit damaging the system.

variable initialization; 
while (condition to control loop) { 
    statement 1; 
    statement 2;
    if (condition outside of loop == true) {

There you have it! Loops and arrays will make your code more flexible, and allows you to do more with less code.

Arrays Versus Many Variables

It’s important to remember that arrays are the most useful when dealing with a group of data. For example, if you wanted to log what you did throughout the day, having an “activities” array could be beneficial.

activity[0] = "Ate breakfast"
activity[1] = "Got dressed"
activity[2] = "Went to work"

This make sense, because all items are related since they’re all actions being taken throughout the day. If you need to output the data at some point, you know it’s all related to some sort of collection of data. Arrays are less useful when storing unrelated data such as:

unrelated[0] = "Ate breakfast"
unrelated[1] = "1789.25"
unrelated[2] = "My car is red"
unrelated[3] = 1950

You can see how the last array is very difficult to do anything with, due to the nonsensical nature of the data. When storing a series of unrelated items, it's usually more feasible to store them as individual variables, such as the code below.

var firstTask = "Ate breakfast"
float bankBalance = "1789.25"
var secretPhrase = "My car is red"
int birthYear = 1950

Declaring variables like this for each piece of data is OK when you have a fixed number of variables. If you need flexibility in your data storage then this might not help either.

Of course, is this article we’re dealing with standard arrays called “indexed” arrays. In future we’ll explore “associative” arrays, which can be useful when storing less cohesive sets of data due to their descriptive nature. While some languages create and use associative arrays the same way as indexed arrays, they aren’t simple to deal with in all languages, so we’ll cover them another time.