Reputation: 305
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.
Upvotes: 0
Views: 792
Reputation: 28826
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
Upvotes: 2
Reputation: 2416
There are a few mistakes in the code provided:
count
, but the actual value cannot be found in the file, so count=0
. For this reason, the for
loop which reads the data from the file is never executed. You either read it from a file or from the keyboard (in the solution below, I chose the second option);readln
when you read from the file. readln
moves the cursor on the next line after it reads the data. This means that only the first number, 9, is stored into numb
. Replace readln
with read
;for
loop, you say that if ... then
. If you want all the three instructions to be executed (and I think you do, because it's an exchange of values), put them between begin
and end
. Otherwise, only the first instruction is executed if the condition is true, the others are always been executed;max
, which initially gets the value of the first element in the array, then you cycle in the remaining values to see if a value is higher than max
.The final code looks like this:
program file1;
uses crt;
var i,count,help, max:integer;
numb:array [1..9] of integer;
f:text;
begin
clrscr;
assign(f,'file1.txt');
reset(f);
writeln('Please input a number for count :');
readln(count);
for i:=1 to count do
read(f,numb[i]);
close(f);
max:=numb[1];
for i:=2 to count do
if numb[i]>max then
max:=numb[i];
write('The result is: ',max);
readln;
end.
Upvotes: 2