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