Lecture 13: Arrays


Array

Imagine that we want to write a program to calculate the average of 10 numbers. With the knowledge we gained until now, we could do this by defining ten different variables, for instance
  float a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;
  float average;
and in the program code:
  average = (a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) / 10.0;
I hope you will agree that this is very cumbersome. And, it could be even worse: imagine we want the user to select how many numbers to use in the calculation of the average:
  int n;

  scanf("%d", &n);
  switch (n)
   {
     case 1: average = a1;
             break;
     case 2: average = (a1 + a2) / 2.0;
             break;
     case 3: average = (a1 + a2 + a3) / 3.0;
             break;
          |
     case 10: average = (a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) / 10.0;
    }
For these purposes exist the arrays. An array lets us define a set of variables of the same type with an easy way of access, namely with an index. Just like in mathematics, ai is the i-th element of vector or series a, a[i] gives the i-th element of array a.
 
 An array is a set of indexed variables of the same type


Declaration of an array

To declare an array we use the following syntax:
 
 type name[numelement] ; 

name is the identifier of the array, just like a name for other variables.
numelement defines the number of elements in the array. The elements run from 0 to numelement-1. This is a little confusing for beginning programmers, who are used to indices from 1 to n.
type is any variable type, for instance float or int.

Examples:

   float account[100];
This might be used to store the information of 100 bankaccounts.

   long int prime[10];
This might be used to store the first 10 prime numbers..

   int propinas[2000];
This might be used to store some simple information of the status of the students with numbers between 0 and 1999, for instance if they paid their tuition fees or not.


Use of an array

Inside the program we can use the elements of an array. 
 name[index]

name[index] will return the value element number index of the array name. This is then a value of the type as described in the declaration of the array. Examples of the arrays declared in the previous section:

   account[20]
is the value - of type float - of element 20 of the array with name account.

   prime[8]
is the value - of type long int - of element 8 of the array prime. The figure on the right might represent this array, so element number 8 would be equal to 19. Of course, our program has to fill this array in some way before the array really contains the prime numbers.

   propinas[1055]
is 1 or 0 (type int). Element 1055 of the array propinas. Did student 1055 pay his tuition fees? Probably our university administration has somewhere in their computers an array with this information.

We can also use a variable for the index in addressing a single element of an array. Naturally, this variable needs to be of any integer type, because the index is something countable; index 3.4981 does not make sense. Index 3 does, it will address the third element of the array. The following code will show the entire array of 20 accounts:

  for (i=0; i<20; i++)
    printf("%f\n",account[i]);
 


Multiple arrays

Just like in mathematics, where we have vectors (tensors of 1 dimension) and matrices (tensors of 2 dimensions) we can have arrays of 1 dimension or 2 dimensions or even more. We can specify this in the following way, for instance a 'double array' (an array of two dimensions):
 
 type name[numindex1][numindex2]; 

The use of a double array is similar to that of a single array. We separate the indices with a comma, or by putting them in separate square parenthesis:
 

 name[index1][index2

 
  As an example: to write the matrix of the figure on the left we might do the following in a complete program. Note that the array consists of 9 (3x3) elements of type integer.

void main()
{
  int  matrix[3][3];

  matrix[0][0] = 1;
  matrix[0][1] = 0;
  matrix[0][2] = 1;
  matrix[1][0] = 2;
  matrix[1][1] = 2;
  matrix[1][2] = 0;
  matrix[2][0] = 1;
  matrix[2][1] = 0;
  matrix[2][2] = 1;
  for (i=0; i<3; i++)
    {
      for (j=0; j<3; j++)
        printf("%d ", matrix[i][j]);
      printf("\n");
    }
}
 


    Caution

  When we are using an array we also have to be careful not to use an index that is 'out of bounds'. This means that we always have to use an index that is less than the total number of elements in the array. If we use a too large index, the results of our program can be very odd. This is best illustrated in an example. The following program defines an array r of 4 integers running from r[0] to r[3], and a normal integer a. The figure on the left shows how they might be placed in memory. What will happen when our program assigns a value to r[4]? If r[4] had existed, it would have occupied the place that is now taken by a, and an assignment to r[4] would be putting a value in the box of what is now occupied by a. Most computer languages don't care and put the value for r[4] there anyway, thereby overwriting the value of a.

  main()
  {
    int a;
    int r[4];

    a = 0;
    printf("a=%d\n", a);
    r[4] = 1;
    printf("a=%d\n", a);
  }

The output of the program will probably be

  a=0
  a=1

Some programming languages can check for this at run-rime. This is called range-checking and when the program tries to use a wrong index, a message 'range-check error' or 'array index out of bounds' will be displayed. The disadvantage of doing this is that the program becomes slower and the compiled program will occupy more space in memory and on disk.

Note: it depends on the exact implementation of the language/compiler. With some languages, it will overwrite the variable declared before the array as in the example above, while in other languages it will overwrite the variable after the array. You can find out by declaring the variables
    int a;
    int r[4];
    int b;
and see if r[4] overwrites a or b.



"Hurray! I know everything about arrays."

Peter Stallinga. Universidade do Algarve, 12 November 2002