Hello, I have been asked to create a pascal program but I am finding it really difficult because I haven't dealt with text files or binary searches before.
The program is supposed to read a Student ID and then the program should display the Student's details. All of the data will be stored on a text file. I'm guessing an array will have to be used to store data of the text file?
The text file contains data like this:
1 Angelica Adams
2 Lloyd Flanders
3 Richard Smith
If someone wanted to know who the third person to apply to a course was. they would need to enter "3" and "Richard Smith" should appear.
The program will eventually have 50 entries/records.
I found something on binary searches but cannot use it because I don't know how to assign lines of the text files to different elements of the array. I'm probably doing it all wrong but here's the code I have got so far:
Program StudentRegister;
Uses
WinCrt;
Var
f: Text;
i: Integer;
StringArray: Array[0..50] of String;
ArrayLength: Integer;
Low: Integer;
Mid: Integer;
High: Integer;
Result: Integer;
StudentID: String;
Label
Break;
Begin
Assign(f, 'filename.txt');
reset(f);
i := 0;
while not eof(f) do
begin
readln(f, StringArray[i]);
write('Enter the Student ID: ');
readln(StudentID);
i := i + 1;
Low := 0;
High := Length(StringArray[i])-1;
Result := -1;
if StringArray[Low] = StudentID then
Result := Low
else if StringArray[High] = StudentID then
Result := High
else while (Low <> High) and (Low+1 <> High) do
begin
Mid := (High-Low) div 2 + Low;
if StringArray[Mid] = StudentID then
begin
Result := Mid;
Goto Break
end else if StringArray[Mid] > StudentID then
High := Mid
else
Low := Mid;
end;
if StringArray[Low] = StudentID then
Result := Low
else if StringArray[High] = StudentID then
Result := High;
if Result = -1 then
writeln('Student No.', StudentID, ' does not exist.')
else
writeln(StudentID, ': ', Result);
end;
Break: Close(f);
ArrayLength := i;
End.
I think my binary search is wrong as "studentid does not exist" appears when I type any number below 2. If I enter numbers greater than 1, the program takes up 99% cpu usage and seems like it has frozen for a short while. If someone can point out what I'm doing wrong, that would be useful.
Any help would be greatly appreciated. Thank you.