Search code examples
arraysloopsadainvariants

Find Maximum Value in Array in Ada


I am doing an Ada program with lots of different functions messing with arrays, i got all my sorting functions going, i am now stuck on retrieving the maximum value in an array using a loop invariant to design the loop for that function. any help?


Solution

  • How about simply looping over the whole array?

    something like this:

    function Get_Maximum (Of : My_Array_Type) return Element_Type is
       Maximum : Element_Type := Of (Of'First);
    begin
       for I in Of'First + 1 .. Of'Last loop
          if Of (I) > Maximum then
             Maximum := Of (I);
          end if;
       end loop;
       return Maximum;
    end Get;
    

    will raise an exception if the array is empty, but this is left as an excercise for the reader, if those cases are needed.