Arrays in Ada

In Ada, an array is a contiguous collection of elements of the same type, indexed by a range of integers. Arrays can be fixed-size or dynamically allocated. Here’s how you can work with arrays in Ada.

with Ada.Text_IO; use Ada.Text_IO;

procedure Arrays is

   -- Here we create an array `A` that will hold exactly 5 integers.
   -- The type of elements and length are both part of the array's type.
   -- By default, an array is initialized to a zero value.
   type IntArray is array (1 .. 5) of Integer;
   A : IntArray := (others => 0);

begin
   Put_Line("emp: " & IntArray'Image(A));
   
   -- We can set a value at an index using the array(index) := value syntax 
   -- and get a value with array(index).
   A(5) := 100;
   Put_Line("set: " & IntArray'Image(A));
   Put_Line("get: " & Integer'Image(A(5)));

   -- The length of an array in Ada can be obtained using the 'Length attribute.
   Put_Line("len: " & Integer'Image(A'Length));

   -- Use this syntax to declare and initialize an array in one line.
   B : IntArray := (1, 2, 3, 4, 5);
   Put_Line("dcl: " & IntArray'Image(B));

   -- Dynamically sized arrays can be defined using the 'Unconstrained array type 
   -- and set later with a specific size.
   type DynArray is array (Positive range <>) of Integer;
   C : DynArray := (1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
   Put_Line("dyn: " & DynArray'Image(C));

   -- Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.
   type TwoDArray is array (1 .. 2, 1 .. 3) of Integer;
   D : TwoDArray := (others => (others => 0));
   
   for I in D'Range(1) loop
      for J in D'Range(2) loop
         D(I, J) := I + J;
      end loop;
   end loop;
   Put_Line("2d: " & TwoDArray'Image(D));

   -- You can also initialize multi-dimensional arrays in one go.
   D := ((1, 2, 3), (1, 2, 3));
   Put_Line("2d: " & TwoDArray'Image(D));

end Arrays;

To compile and run the Ada program, use the following commands:

$ gnatmake arrays.adb
$ ./arrays
emp: (0, 0, 0, 0, 0)
set: (0, 0, 0, 0, 100)
get: 100
len: 5
dcl: (1, 2, 3, 4, 5)
dyn: (1, 2, 3, 4, 5)
2d: ((2, 3, 4), (3, 4, 5))
2d: ((1, 2, 3), (1, 2, 3))

Next example: Slices.

查看推荐产品

Comments powered by Disqus