Wednesday 26 May 2010

Dynamic Array

Dynamic array is an array that has no fix amount. To declare a dynamic array you can use this syntax :

Array of datatype;

Example :

    Var

       MyArray : array of integer;

This array is dynamic with integer data type. The memory of array is not allocated. To allocate memory of array use SetLength procedure.

Example :

    SetLength(MyArray, 5);

    SetLength(MyArray, 2, 3);

    SetLength(MyArray, 2, 3, 5);

It will allocate an array which has five elements. In this case the index will be 0, 1, 2, 3, 4. And to free the array memory, set nil value to the array. 

Example :

    MyArray := nil;

Example program :

program Project1;
{$APPTYPE CONSOLE}
uses
   SysUtils;

var
   i, sum : integer;
   MyArray : array of integer;
begin
  SetLength(MyArray, 5);
  MyArray[0] := 12;
  MyArray[1] := 14;
  MyArray[2] := 16;
  MyArray[3] := 18;
  MyArray[4] := 20;
  sum := 0;
  for i:= 0 to Length(MyArray) -1 do
   begin
     sum := sum + MyArray[i];
   end;
  writeln(sum);
  readln; 
end.

You can download the complete code here.

0 comments:

Post a Comment

These links are part of a pay per click advertising program called Infolinks. Infolinks is an In Text advertising service; they take my text and create links within it. If you hover your mouse over these double underlined links, you will see a small dialog box containing an advertisement related to the text. You can choose to move the mouse away and go on with your browsing, or to click on the box and visit the relevant ad. Click here to learn more about Infolinks Double Underline Link Ads.