Previous topic | Ada Home Page | Index

File of integers - example

-- given a file of integers, one per line, find the
-- average of the integers


with TEXT_IO;
procedure average is

    package int_io is new TEXT_IO.INTEGER_IO(INTEGER);
    package flt_io is new TEXT_IO.FLOAT_IO  (FLOAT);
    use TEXT_IO, int_io, flt_io;

    num : INTEGER;         -- one integer from the file
    sum : INTEGER := 0;    -- sum of the integers
    N   : NATURAL := 0;    -- how many integers?
    avg : FLOAT;           -- average of the integers

begin -- average

    while not END_OF_FILE loop

        -- read and tally the next integer
        GET (num);
        sum := sum + num;
        N   := N   + 1  ;
    end loop;

    -- compute and print the average
    if N = 0 then
        PUT_LINE ("No data, so no average");
    else
        avg := FLOAT(sum) / FLOAT(N);
        PUT ("The average is ");
        PUT (avg, EXP=>0, FORE=>6, AFT=> 1);
        NEW_LINE;
    end if;
end average;

This is similar in form to processing a file of lines, without worrying about the structure of a line as a sequence of characters.


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