Contents

Loops and Arrays

Computers are good at performing repetitive tasks over large sets of data. In this chapter we’ll discuss how to write computer programs that can repeat operations using loops. We’ll also look at how to store large amounts of data using arrays. By combining loops and arrays, we can write computer programs that can process batches of data.

Looping

One thing that makes computers valuable is their ability to repeat the same operation consistently, accurately, and reliably. This is valuable because us humans are, generally speaking, not consistent, accurate, or reliable! Ask someone to come to your house at 5pm, and you’ll most likely see them at 5 past, 10 past, half past…Perhaps even an hour late!

For social events, that’s fine - but when it comes to situations where consistency is critical, it’s obviously not ok.

Let’s take a real-world example - auto pilot software on an airplane. Being a pilot on a long distance flight is probably quite dull in some ways (not that I’m speaking from experience!). The view is repetitive, nothing interesting happens, and you have to be alert for hours at a time. However, you can’t just sit back and relax - even the slightest slip in attention and you might miss a critical piece of information from the dashboard of the plane, which might cost the lives of everyone on board!

Computers don’t have the problem of getting bored and wanting to go to sleep. Computers are happy to stare at a dashboard for hours and hours at a time, and raise an alert if a critical measure reaches a dangerous level. A computer can continuously perform the same check many times a second without getting tired. Therefore we can trust auto-pilot software to take care of monitoring all the various information related to flying the plane.

Like a broken record

It may not seem obvious, but most things computers do involves repeating the same instruction over and over. let’s look at another real word example - music playing software.

When you double click a music file on your computer, it will automatically fire up some kind of media player. The media player software will look at the music file and inspect the data. The software will read a chunk of the data and relay it to the speakers in order to emit sound. That chunk of data might only represent a fraction of a second’s worth of sound, so the computer will have to repeatedly relay information to the speaker for the music to sound correct.

The logic of the media player might look something like this:

Read the music file
Split the music file data into chunks
For every chunk of music data
    Relay the data chunk to the speakers
    Wait for the speaker to finish playing
Loop back until all data chunks have been played

In computer programming, this sort of operation is known as a loop.

The basic principle behind a loop is to repeat a set instructions until a condition is met. In this case, the instructions to send data to the speakers are repeated. The condition to terminate the loop is met when all the data has been sent to the speakers.

The process of looping over a data set is generally known as iteration. So you could say ‘we iterate over the music data and relay it to the speakers’.

Arrays

It doesn’t make sense to repeat instructions unless the data that the instructions are operating on changes. In the above example, the music data chunk changes each time the loop goes round. If that wasn’t the case the speakers would play the same sound repeatedly, which would be annoying to say the least!

To help with this, computer programming languages have the concept of an array. An array is a group of data, where each item of data is associated with a numerical index. Data in the array can be accessed by querying the array with an index.

An array that contains the names of people can be visualized like so:

image

The first index, 0 contains, "Alice". The second index, 1, contains "Bob", and so on.

An array could also be thought about like a set of houses on a road, where each house has a number. If you go to house number 1, you’ll meet Bob. If you go to house number 3, you’ll see Dan. But if you look for house number 15 when there are only four houses on that road, you won’t meet anyone!

Arrays are repetitive data structures, so it makes sense to use a loop to operate on the data inside them. A loop can look at the data at each index of an array, and perform the same instruction on each item of data.

Each programming language has a different approach to arrays and loops, so it’s difficult to speak generally about them. Let’s just see how they work in C#.

Loops in C#

In C#, there are three main types of loop. The for loop, the while loop, and the do...while loop.

The while loop

The while loop is probably the simplest:

int x = 0;

while (x < 3) {
    Console.WriteLine("While: " + x);
    x++;
}

The while loop has two main components - a loop condition, and a body.

In this example, the loop condition is (x < 3). So, while (x < 3) remains true, execute the code inside the loop.

In the body of the while loop, we output some text. On the final line of the loop, x is increased by one. This is done with the ++ operator - known as the increment operator. So x++ means, increase, or increment, x by one.

The computer will then go back up to the start of the loop and check the loop condition. x started off as 0, but has been incremented by one - so now x is 1. (x < 3) is still true however, therefore the loop goes round again. This will continue until x is 3, at which point (x < 3) will be false, and the loop will exit.

The while loop basically says ‘do this while a condition is true’. So in the above example, Hello! is outputted while x is less than 3.

The do...while loop

The do...while loop is only slightly more complicated:

int x = 0;

do {
    Console.WriteLine("Do while: " + x);
    x++;
} while(x < 3);

It’s very similar to the while loop we just saw - but there is a subtle difference.

In the do...while loop, the condition is checked after the loop is entered - whereas in the while loop, the condition is checked before the loop.

This means that the body of a do...while loop will always execute at least once, since the condition is only checked after the first iteration.

This is an important distinction. Compare the outputs of the two loops:

While: 0
While: 1
While: 2
Do while: 0
Do while: 1
Do while: 2

They’re the same, right? Ok, let’s change the program so that x starts off as 5. In that case you would get the following output:

Do while: 5

Why doesn’t the while loop output anything? Well, in the do...while loop, the loop condition is checked last. This means the body of the loop is executed once before even checking the loop condition.

The while loop, on the other hand, checks the loop condition first. It immediately skips over the loop since the condition is already false.

The key difference is that the body of the do..while loop is always executed at least once, whereas the body of while loop may never be executed at all.

for loops

The for loop is quite different to the while and do..while loop. The basic principle behind a for loop is that it iterates a set number of times. The for loop keeps track of the current iteration using a loop counter. The loop counter usually starts at 0, and is incremented after each iteration. The for loop then terminates once the loop counter has reached a certain value defined by the programmer.

In C#, a for loop looks like this:

for (int x = 0; x < 3; x++) {
    Console.WriteLine("For: " + x);
}

There’s a lot going on here, so let’s break it down:

  • for - this starts the loop
  • int x = 0; - we declare a variable, x, and set it’s initial value as 0. x will serve as the loop counter
  • x < 3 - this is the loop condition. The for loop will continue to run while this condition is true
  • x++ - This instruction is executed after each iteration. In this case, x will be incremented by one

This for loop will therefore have the following output:

For: 0
For: 1
For: 2

The for loop is useful as the loop counter is built into the structure of the loop itself. This is unlike the while and do...while loop, where we had to declare x outside of the loop.

The main advantage of a for loop is that you can easily set the number of iterations. This makes the for loop convenient to use with arrays, as we’ll see shortly.

Arrays in C#

As previously explained, an array is a group of data, where each item of data is associated with a numerical index. Data in the array can be accessed by querying the array with an index.

Arrays are important because they allow us to group related, yet repetitive items of data together.

Say for example we wanted to define a list of products for a stock tracking application in a shop. Just using variables, it might look something like this:

string itemOne = "Computer";
string itemTwo = "Desk chair";
string itemThree = "Printer";

A stock tracking program might potentially have to keep track of hundreds, thousands, or tens of thousands of items. Therefore writing code like this would make our programs very long and difficult to understand. Arrays are one way of managing repetitive data like this.

In C#, arrays have two important properties:

  • They are of a fixed size
  • Every item in the array has the same type

An array is declared like so:

string[] productsArray = new string[3];

This is similar to a variable declaration, but with some important differences.

First, we use string[] instead of just string. The square brackets mean that this type is now an array. So productsArray is not of type ‘string’ - it’s of type ‘string array’.

Instead of assigning a string value, we instead initialize the array with a size. The size is determined by the number in the second set of square brackets. So new string[3] means ‘an array of strings with 3 spaces’.

We also use the new keyword. This is to do with something called Object Oriented programming, that we’ll look at in later chapters.

Putting data into an array

The C# code to put data into an array looks like this:

productsArray[0] = "Computer";

This is very similar to how we assign values to variables. The only difference is that you must provide an index, which is the place in the array to put the data.

The above code places "Computer" in productsArray at index 0 - which is the first space. We specify the index with the number in the square brackets.

You can access items in an array similarly:

string computer = productsArray[0];

This snippet of code will declare a variable, computer and assign it the value of productsArray[0] - which happens to be "Computer".

Arrays and for loops

I said earlier that arrays and for loops work very well together. This is because we can use the loop counter of the for loop to index into an array.

Let’s look at an example of how this works:

string[] productsArray = new string[3];
productsArray[0] = "Computer";
productsArray[1] = "Desk chair";
productsArray[2] = "Printer";

for (int x = 0; x < 3; x++) {
    Console.WriteLine(productsArray[x]);
}

In this example we create a new string array, and assign values to each index. We then use the for loop to output each product in the array to the Standard Output.

Let’s step the code in more detail:

  • Declare productsArray with a size of 3.
    • productsArray stores data of type string
  • Assign the 0th, 1st, and 2nd indexes of productsArray with some products
  • Start the for loop
    • Declare a loop counter, x, and initialize as 0
    • Set the loop condition such that the loop continues if x is less than 3
    • On each iteration of the for loop, x will be increased by one
  • Enter the for loop
    • Write productsArray[0] to the console
    • Go back to the start of the for loop
    • Increment x, so now x is 1
    • Check if x is less than 3
    • x is 1, so continue
  • Start the for loop again
    • Write productsArray[1] to the console
    • Go back to the start of the for loop
    • Increment x, so now x is 2
    • Check if x is less than 3
    • x is 2, so increment x and continue
  • Start the for loop again
    • Write productsArray[2] to the console
    • Go back to the start of the for loop
    • Increment x, so now x is 3
    • Check if x is less than 3
    • x is not less than 3, so exit

This produces the following output:

Computer
Desk Chair
Printer

In the next Kata, you’ll learn how to use arrays and loops for yourself.

Copyright Mikiel Agutu 2019