Loading search index…
No recent searches
No results for "Query here"
Arrays in Pascal are numbered sequences of elements of a specific length. They are commonly used in Pascal programming.
program ArrayExample; uses SysUtils; var a: array[0..4] of Integer; b: array[0..4] of Integer; twoD: array[0..1, 0..2] of Integer; i, j: Integer; begin // By default, an array is zero-valued, which for Integers means 0s. WriteLn('emp: ', '[', a[0], ' ', a[1], ' ', a[2], ' ', a[3], ' ', a[4], ']'); // We can set a value at an index using the array[index] := value syntax, // and get a value with array[index]. a[4] := 100; WriteLn('set: ', '[', a[0], ' ', a[1], ' ', a[2], ' ', a[3], ' ', a[4], ']'); WriteLn('get: ', a[4]); // The Length function returns the length of an array. WriteLn('len: ', Length(a)); // Use this syntax to declare and initialize an array in one line. b := [1, 2, 3, 4, 5]; WriteLn('dcl: ', '[', b[0], ' ', b[1], ' ', b[2], ' ', b[3], ' ', b[4], ']'); // In Pascal, we can't have the compiler count the number of elements for us, // so we need to specify the size explicitly. // In Pascal, we can't specify indexes like in Go, but we can initialize // specific elements and leave others as default. b[0] := 100; b[3] := 400; b[4] := 500; WriteLn('idx: ', '[', b[0], ' ', b[1], ' ', b[2], ' ', b[3], ' ', b[4], ']'); // Array types are one-dimensional, but you can create multi-dimensional arrays. for i := 0 to 1 do for j := 0 to 2 do twoD[i, j] := i + j; Write('2d: '); for i := 0 to 1 do begin Write('['); for j := 0 to 2 do begin Write(twoD[i, j]); if j < 2 then Write(' '); end; Write(']'); if i = 0 then Write(' '); end; WriteLn; // You can create and initialize multi-dimensional arrays at declaration. twoD := ((1, 2, 3), (1, 2, 3)); Write('2d: '); for i := 0 to 1 do begin Write('['); for j := 0 to 2 do begin Write(twoD[i, j]); if j < 2 then Write(' '); end; Write(']'); if i = 0 then Write(' '); end; WriteLn; end.
Note that arrays in Pascal are displayed in a custom format when printed with WriteLn. We’ve mimicked the Go output format for consistency.
WriteLn
To run the program, save it as arrays.pas and use a Pascal compiler like Free Pascal:
arrays.pas
$ fpc arrays.pas $ ./arrays emp: [0 0 0 0 0] set: [0 0 0 0 100] get: 100 len: 5 dcl: [1 2 3 4 5] idx: [100 0 0 400 500] 2d: [0 1 2] [1 2 3] 2d: [1 2 3] [1 2 3]
Pascal arrays have some differences compared to other languages:
Understanding these characteristics will help you work effectively with arrays in Pascal.