Tutorial - Arrays

From Mesham
Revision as of 13:07, 17 January 2013 by Polas (talk | contribs)
Jump to navigationJump to search

Introduction

An array is a collection of element data in one or more dimensions and is a key data structure used in numerous codes. In this tutorial we shall have a look at how to create, use and communicate arrays.

Simple arrays

function void main() {
   var a:array[Int,10];
};

The above code will declare variable a to be an array of ten Ints which are indexed 0 to 9 inclusively. In the absence of further information a set of default types will be applied which are; heap, onesided, row, allocated, multiple. Arrays, when allocated to the heap, are subject to garbage collection which will remove them when no longer used.

#include <io>
#include <string>

function void main() {
   var a:array[Int,10];
   var i;
   for i from 0 to 9 {
      a[i]:=i;
   };
   for i from 0 to 9 {
      print(itostring(a[i]));
   };
};

The code snippet demonstrates writing to and reading from elements of an array, if you compile and run this code then you will see it displays values 0 to 9 on standard output. We can access an element of an array (for reading or writing) via the [x] syntax, where x is either an Int constant or variable.

Arrays and functions

#include <io>
#include <string>

function void main() {
   var a:array[Int,10];
   fill(a);
   display(a);
};

function void fill(var a:array[Int,10]) {
   var i;
   for i from 0 to 9 {
      a[i]:=i;
   };
};

function void display(var a:array[Int]) {
   var i;
   for i from 0 to 9 {
      print(itostring(a[i]));
   };
};

This code demonstrates passing arrays into functions and there are a couple of noteworthy points to make here. First, because an array is, by default, allocated to the heap, as discussed in the functions tutorial, this is pass by reference. Hence modifications made in the fill function do affect the original data allocated in the main function, which is what we want here. Secondly, see that the type we provide to the display function does not have any explicit size associated with the array? It is not always possible to know the size of an array that is being passed into a function, so Mesham allows for the type of a function argument to be specified with a size but with two restrictions; first it must be a one dimensional array and secondly no compile time bounds checking can take place.