A compiler for Ada



Example Program

  • Block structure using begin/end

  1. -- Ada Example Program
  2. -- Input: An integer, List_Len, where List_Len is less
  3. -- than 100, followed by List_Len-integer values
  4. -- Output: The number of input values that are greater
  5. -- than the average of all input values
  6.  
  7. with Ada.Text_IO, Ada.Integer.Text_IO;
  8. use Ada.Text_IO, Ada.Integer.Text_IO;
  9.  
  10. procedure Ada_Ex is
  11. type Int_List_Type is array (1..99) of Integer;
  12. Int_List : Int_List_Type;
  13. List_Len, Sum, Average, Result : Integer;
  14. begin
  15. Result:= 0;
  16. Sum := 0;
  17. Get (List_Len);
  18. if (List_Len > 0) and (List_Len < 100) then
  19. -- Read input data into an array and compute the sum
  20. for Counter := 1 .. List_Len loop
  21. Get (Int_List(Counter));
  22. Sum := Sum + Int_List(Counter);
  23. end loop;
  24. -- Compute the average
  25. Average := Sum / List_Len;
  26. -- Count the number of values that are > average
  27. for Counter := 1 .. List_Len loop
  28. if Int_List(Counter) > Average then
  29. Result:= Result+ 1;
  30. end if;
  31. end loop;
  32. -- Print result
  33. Put ("The number of values > average is:");
  34. Put (Result);
  35. New_Line;
  36. else
  37. Put_Line ("Error—input list length is not legal");
  38. end if;
  39. end Ada_Ex;


Readability Example

Let's imagine that you want to create a generic package for a Stack that takes operations Push and Pop. Here's one way to define such a Stack; we'll define a Stack package that stores some Item type and has a maximum size.

Somewhere else you can instantiate the Generic_Stack package. If you wanted to instantiate a new package called ``Stack_Int'' which could hold 200 Integers, you could say:

     package Stack_Int is new Generic_Stack(Size => 200, Item => Integer);

The ``Size =>'' and ``Item =>'' are optional; you could omit them if you wanted to, but including them makes the code clearer. From then on, you could "Push" a new Integer onto Stack_Int by saying:

     Stack_Int.Push(7);

  1. generic
  2. Size : Positive;
  3. type Item is private;
  4. package Generic_Stack is
  5. procedure Push(E : in Item);
  6. procedure Pop (E : out Item);
  7. Overflow, Underflow : exception;
  8. end Generic_Stack;
  9.  
  10. package body Generic_Stack is
  11. type Table is array (Positive range <>) of Item;
  12. Space : Table(1 .. Size);
  13. Index : Natural := 0;
  14.  
  15. procedure Push(E : in Item) is
  16. begin
  17. if Index >= Size then
  18. raise Overflow;
  19. end if;
  20. Index := Index + 1;
  21. Space(Index) := E;
  22. end Push;
  23.  
  24. procedure Pop(E : out Item) is
  25. begin
  26. if Index = 0 then
  27. raise Underflow;
  28. end if;
  29. E := Space(Index);
  30. Index := Index - 1;
  31. end Pop;
  32.  
  33. end Generic_Stack;