1

PROBLEM STATEMENT

I would like to iterate over every element in a matrix and display:

  • The Element Value
  • The Element Index (I, J)

The code below gives me the following output:

(-2147483648, -2147483648) =  1.00000E+00
(-2147483648, -2147483647) =  2.00000E+00
(-2147483648, -2147483646) =  3.00000E+00
(-2147483647, -2147483648) =  4.00000E+00
(-2147483647, -2147483647) =  5.00000E+00
(-2147483647, -2147483646) =  6.00000E+00

I would expect to see 1 instead of -2147483648 and 2 instead of -2147483647.

SAMPLE CODE

with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Text_IO;              use Ada.Text_IO;

procedure Index is
   Matrix : Real_Matrix := (( 1.0, 2.0, 3.0 ),
                            ( 4.0, 5.0, 6.0 ));
begin
   for I in Matrix'Range(1) loop
      for J in Matrix'Range(2) loop
         Put_Line("(" & Integer'Image(I) & ", " &
                   Integer'Image(J) & ") = " &
                   Float'Image(Matrix(I, J)));
      end loop;
   end loop;
end Index;
John Leimon
  • 1,063
  • 1
  • 9
  • 13
  • 3
    Apparently the Real_Matrix type uses `Integer` as its index type - and the default value if not otherwise specified is `Integer'First`. In Ada you are encouraged to declare and use your own types appropriate to your problem, so declare an array type (along the lines of Real_Matrix) with Natural (starts at 0) or Positive (you get it) or a ranged subtype, and use that. –  Dec 05 '16 at 21:35

1 Answers1

5

The index type of Real_Matrix is Integer, which starts at -2147483648 on your platform, which explains the numbers you are seeing. However, since the type is unconstrained, you can specify your own index in an array aggregate:

Matrix : Real_Matrix := ( 1 => ( 1 => 1.0, 2 => 2.0, 3 => 3.0 ),
                          2 => ( 1 => 4.0, 2 => 5.0, 3 => 6.0 ));
egilhh
  • 6,464
  • 1
  • 18
  • 19