pascalfreepascalturbo-pascal

How to find the biggest number from a txt file?


I have to find out the biggest number from a txt file. Numbers are for example:

9 8 7 6 5

Someone told me, that it should works, but it didn't, and I have no clue how to work with file bcs.

program file;
uses crt;
var i,count,help:integer;

numb:array [1..9] of integer;
f:text;

begin
clrscr;

 assign(f,'file1.txt');
 reset(f);

   readln(f,count);

   for i:=1 to count do

    readln(f,numb[i]);

 close(f);

 for i:=2 to count do
  begin

   if (numb[i-1] < numb[i]) then

     help:=numb[i-1];

     numb[i-1]:=numb[i];

     numb[i]:=help;

  end;  

 for i:=1 to count do
  begin

   write(numb[i]);
  end;

readln;
end.

Solution

  • If you only want to know the highest number, you can use a running maximum while reading the numbers in the file.

    As a user you don't have to know how many numbers there are in the file. The program should determine that.

    I wrote a little test file, called file1.txt:

    9 8 7 6 3 11 17
    32 11 13 19 64 11 19 22
    38 6 21 0 37
    

    And I only read the numbers, comparing them with Max. That is all you need.

    program ReadMaxNumber;
    
    uses
      Crt;
    
    var
      Max, Num: Integer;
      F: Text;
    
    begin
      ClrScr;
      Assign(F, 'file1.txt');
      Reset(F);
    
      Max := -1;
      while not Eof(F) do
      begin
        Read(F, Num);
        if Num > Max then
          Max := Num;
      end;
    
      Close(F);
      Writeln('Maximum = ', Max);
      Readln;
    end.
    

    When I run this, the output is as expected:

    Maximum = 64