Factorial in Ada

Example for versions gnat 3.4.5, gnat 4.3.2

This example uses recursive factorial definition.

Note that there are different packages for printing text, integers and long integers. put command generally accepts several arguments: Item is the number/string to print, Width is the number of positions to use, Fore and Aft are the numbers of decimal digits to be printed before and after decimal separator etc. If there is only one argument, it is considered to be Item. Setting Width to a number which is less than the actual length of the number prints it without leading spaces (which is the default for Ada).

Another thing to note is that Ada doesn’t support implicit data type conversions, so to calculate N*Fact(N-1) one has to convert N to Long_Long_Integer explicitly first.

with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Long_Integer_Text_IO;

procedure Factorial is
      function Fact (N: Integer) return Long_Long_Integer is
         if N=0 then
            return 1;
            return Long_Long_Integer(N)*Fact(N-1);
         end if;
      end Fact;
   i: Integer := 0;
         Ada.Integer_Text_IO.Put (Item => i, Width => 1);
         Ada.Text_IO.Put ("! = ");
         Ada.Long_Long_Integer_Text_IO.Put (Item => Fact(i), Width => 1);
         i := i + 1;
         exit when i=17;
      end loop;
end Factorial;