Version 0.55.1

Arrays and Loops

This section discusses the concept of data arrays as a way to store many data elements without much effort and loops to scan over these.

Arrays

Multiple variables of one data type can be packed together in a variable list or array. In this list, each variable is identified by a unique index value. Typical for the definition of an array are the squared brackets '[' and ']' that contain the number of elements the array should store. The following example creates an array with five integer values:

Example

int i[5]

Of course we can create arrays of other data types as well. Lets denote the number of elements (in this case 5) as N to be more general. If an array has N elements, the index values of the elements of the array range from 0 to N-1. After the array has been defined, the squared brackets are used to contain the index values of the very element that is addressed by the expression:

Example

int i[5]
i[0] = 10
i[1] = 20
i[2] = 40
i[3] = 197
i[4] = 200
echo( i[2] )

Output

40

The example assigns each element of the array another value and outputs the third. Note that the value N (in this case: 5) cannot be used as an index of an element since it is already out of range.

The elements of an array can be addressed in an arbitrary order. The index value can be expressed by another variable what is useful when performing loops.

Short hand notation

In the previous example, each entry of the array was set in a single line. Since this might be tedious for larger arrays, a short hand notation exists to achieve the same result:

Example

int i[] = [10, 20, 40, 197, 200]
echo( i[2] )

Output

40

Here, the array with its N values is defined on the right-hand-side of the equation. Note that the the squared brackets behind the declaration of i are empty.

Since this short hand notation can be used in all places of the code, it might not always be clear what data type the array shall be of. Therefore the following rules apply:

  • the data type of the elements of an array in short hand notation can be placed before the array in pointy brackets
  • if this explicit definition of the data type is missing, the first element inside the short hand notation determines the element data type

In an example this looks like this:

Example

echo( <string>[5, 6.3] )
echo( [5, 6.3] )

Output

["5","6.3"]
[5,6]

Length of an array

The length of an array refers to its number of elements N. It can be checked by the length member function of the array: by writing the array name followed by a dot and the function name length() we can get the value of N:

Example

int i[5]
echo( i.length() )

Output

5

This is especially useful if we did not create the array by ourselves but got it from another source.

Other operations on arrays.

There are a few more member operations that can be used to modify the structure of an array:

Array member function Description
int erase( int n ) Removes the element with index n from the array.
push_back( dtype e ) Adds one element e to the end of the array. This increases the array length by one.
resize( int n ) Changes the size of the array to a new size size.

Multidimensional arrays

Suppose we want to address each tile of a chess board. We could create an array of 64 elements and map the indices as following: a1 = 0, a2 = 1, ... ,a8 = 7, b1 = 8, ... ,h8 = 63. Addressing the field f2 would include a certain amount of calculation to get the array index value: f is the sixth letter of the alphabet, giving it an index of 5. The row 2 has an index of 1. 5 * 8 (the number of elements per column) + 1 = 41. As an alternative, we can let the computer do the calculation for us by defining an 8 x 8 two-dimensional array:

Example

int i[8][8]

This allows us to address the field f2 directly by using its column index value 5 and row index 1:

Example

int i[8][8]
i[5][1] = 4

It is also possible to define arrays with a dimension larger than two. If the array gets addressed with fewer indices than its dimension, it returns an array of the remaining dimension. We could expand the chess board example to having 15 rooms with 20 chess boards each. This could addressed like that:

Example

int i[15][20][8][8]     // Array for storing values on 20 chessboards in 15 rooms.
int j[8][8]             // Another chess board array.
j = i[3][13]            // Copy the 14. (index 13) chess board of room 4 (index 3) into j.
echo( i[12].length() )    // Output the number of chess boards in room 13 ( index 12).

Output

20

Like in the case of one-dimensional arrays, the short hand notation can be used to fill multidimensional arrays at once:

Example

int i[][] = [[1,2],[2,3],[3,4]]

Empty arrays

In some cases one wants to define a one- or more-dimensional array that contains no elements. This might be the case when using an array as an open parameter. That goal can be achieved in three different ways. The first is to explicitly set the size of the respective dimension to zero:

Example

int i[0]

The same thing can be achieved by leaving out the length at all:

Example

int i[]

The third way uses the short hand notation that doesn't require a variable name. The data type of the array must be given in pointy brackets in front of the array:

Example

<int>[]

See also the reference about arrays.

Loops

Often it is required to perform a task multiple times or to scan over each element of an array. The method of choice for such tasks is to use loops. These are control commands that perform a given part of code repeatedly until a certain condition is fulfilled or a break-off command is encountered.

Loops with while

The while loop has the form while( condition ) statement. It repeatedly executes the statement as long as the condition, a boolean value, is found to be 'true'. This implies that the statement should change the condition value in order leave the loop. This can be seen in the following example:

Example

int i = 0
while( i < 10 )
  i = i + 1

In the example, the program increases i until it reaches the value 10. Then the condition of the while command evalutes to 'false' what causes the loop to quit.

Remark

Please be aware that a badly constructed loop that does not break off runs "forever" (i.e. until the program is killed externally). This is a common source of "freezing" of a program.

Of course the statement of the while loop can be a code block including other commands, e.g. an echo output:

Example

int i = 0
while( i < 5 )
{
  echo( i )
  i = i + 1
}

Output

0
1
2
3
4

Loops with for

The for loop is an alternative to the while loop. It has the following signature: for( initialization ; condition ; iterator ) statement. It expects three different arguments: the first one is the initialization. This is a statement that is executed before the first cycle is started. This is typically used to initialize a running variable like i in the while loop examples. The second argument is the break-off condition. Like in a while loop, the condition is checked before each iteration and the looping is stopped, if the condition has the value 'false'. The last argument is the iterator statement that is executed after each cycle. Typically the iterator statement is used to increment or decrement the running variable. The statement is executed during each loop iteration.

An example of a for loop would be:

Example

for( int i = 0; i < 5; i++ )
  echo( i )

Output

0
1
2
3
4

In the following example, a for loop is used to scan over an array's elements. The value of each element is then set to be its index:

Example

int i[10]
for( int j = 0; j < i.length(); j++ )
  i[j] = j

The break Command

For both the while and the for loop there is special way of escaping early: the break command. If this command is encountered during the looping, the loop is quit immediately. This can be used to terminate a loop when a certain task is done and no further cycles are required.

In the following example the argument of the while loop is always true, making it technically infinite. Nevertheless, after some cycles the break is encountered when i reaches the value 10. This terminates the loop.

Example

int i = 0
while( true )
{
  if( i == 10 )
    break
  i = i + 1
}

The continue Command

Like the break command, the continue command changes the behavior of a loop when encountered in the statement section. Unlike the break command it does not quit the loop completely but only the current cycle. This means that everything the would normally follow the continue command in the loop's statement block is skipped for this cycle and the next cycle is started. In an example this looks like that:

Example

for( int i = 0; i < 6; i++ )
{
  echo( "Start cycle " + i )
  if( i > 2 )
    continue
  echo( "End cycle " + i )
}

Output

Start cycle 0
End cycle 0
Start cycle 1
End cycle 1
Start cycle 2
End cycle 2
Start cycle 3
Start cycle 4
Start cycle 5

🗙

Search results for