Previous topic | Ada Home Page | Index

Example: Library Units

Library unit - useful procedure

The following procedure reads an integer, repeatedly prompting the user to enter an integer until a value within a desired range is typed. It could be useful in many programs, so it may be worth writing and compiling as a stand-alone unit: a library unit.

(Note that this procedure uses the "int_io" package from the previous example, so that library unit must have been compiled beforehand.)

with TEXT_IO, int_io;

procedure get_integer 
  ( val  : out INTEGER;         -- value entered by the user
    low  : in  INTEGER;         -- low  bound of range
    high : in  INTEGER )        -- high bound of range
is

    use TEXT_IO, int_io;

    num  : INTEGER;             -- number entered by user

begin -- get_integer

    -- only proceed if entry condition satisfied
    if low <= high then
        -- Loop until a valid number is entered
        loop
            -- Prompt for input, showing the desired range
            PUT ("Enter an integer between ");
            PUT (low, WIDTH=>1);
            PUT (" and ");
            PUT (high, WIDTH=>1);
            PUT (" : ");

            -- Read an integer
            GET (num);

            -- exit loop if number is in the desired range
            exit when (low <= num) and (num <= high);

            -- assert: integer is not in range
            -- display an error message
            PUT_LINE ("Out of range: please try again");
        end loop;

        -- return the satisfactory integer that was typed
        val := num;
    else
        PUT_LINE ("Impossible range");
        -- return a dummy value otherwise
        val := 0;
    end if;
end get_integer;


driver program

To use that procedure, all that is needed is to include its name in a WITH statement. (Note that this example also uses the "int_io" package from the previous example, so that library unit must have been compiled beforehand.)

with TEXT_IO, int_io, get_integer;

procedure main is

    use text_io, int_io;

    num : integer;

begin

    PUT ("Please enter a mark ");

    get_integer (num, 0, 100);

    PUT ("You entered ");
    PUT (num);
    NEW_LINE;

end main;


Compilation

Sun ada

  1. adac basic_io.a
  2. adac get_integer.a
  3. adae main.a

gnat ada

  1. gnatcc int_io.ads
  2. gnatcc get_integer.adb
  3. gnatcc main.adb
  4. gnatbl main.ali


Previous topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 17 Feb 1996