# Playing with arrays in Fortran (Part 1)

Arrays in Fortran are fun to deal with. There I said it.

They have to be, because in the world of über number-crunching, arrays matter – so dealing with them in an efficient manner also matters.

### Arbitrary indexing

In Fortran, one is not restricted to using arrays where the indexing begins at 0 – array indexes may start and end at any arbitrary integer. This means you can build a program based on an algorithm, rather than an algorithm based on the syntax of a language. A good example of this is the recursive 8-Queens algorithm [1] published by Niklaus Wirth in 1976. The algorithm uses four arrays to help solve the problem, shown below in Pascal:

```a : array[ 1 .. 8] of boolean;
b : array[ 2 .. 16] of boolean;
c : array[ -7 .. 7] of boolean;
x : array[ 1 .. 8] of integer;```

Writing this code in C would require a complete re-think of the array indexing for all the arrays, and hence the requirement to redo the algorithm. Pascal and Fortran (and even Ada) allow arbitrary indexing, making the task way easier. Here is the equivalent code in Fortran95:

```integer :: x(1:8)
logical :: a(1:8), b(2:16), c(-7:7)```

### Whole array processing

Current versions of Fortran also abide by the array syntax reminiscent of array-based languages. There is no requirement to use verbose loops to process arrays. For example the code in Fortran to add the elements of two arrays a and b and assign them to a third array c, is:

```real :: a(10), b(10), c(10)
c = a + b```

versus the comparable code in C:

```int i,j;
double a[10], b[10], c[10];
for (i=0; i<10; i=i+1)
for (j=0; j<10; j=j+1)
c[i][j] = a[i][j] + b[i][j];```