Pascal: Search for Pupils in List

program pupils_search;
const max = 5;
type pupil_record = record
          name : string[20];
          form : string[3];
          year_of_entry: integer;
        end;
        pupil_array = array [1..max] of pupil_record;
        pupil_data = file of pupil_record;

var   pupils : pupil_array;
        pupil_file : pupil_data;
        x : char;
        choice : integer;

procedure sort_data;
var i, j: integer;
      temp : pupil_record;
begin
  for i := 1 to max -1 do
    for j := i + 1 to max do
      if pupils[i].name > pupils[j].name then 
        begin
          temp := pupils[i];
          pupils[i] := pupils[j];
          pupils[j] := temp;
        end;
end;

procedure get_data;
var i : integer;
begin
  writeln ('Enter details of ', max, ' pupils, name, form and year of entry');
  for i:= 1 to max do
   with pupils[i] do
    begin
      writeln ('Enter name:');
      readln (name);
      writeln ('Enter form:');
      readln (form);
      writeln ('Enter year of entry:');
      readln (year_of_entry);
    end;
  sort_data;
end;

procedure show_data;
var i : integer;
begin
  writeln ('You entered:');
  for i:= 1 to max do
   with pupils[i] do
      writeln ('Name: ', name, ' Form: ', form, ' Year of entry: ', year_of_entry);
end;

procedure save_data;
var i : integer;
begin
  assign (pupil_file, 'pupils.dat');
  rewrite (pupil_file);
  for i:= 1 to max do
    write (pupil_file, pupils[i]);
  close (pupil_file);
end;

procedure retrieve_data;
var i : integer;
begin
  i := 1;
  assign (pupil_file, 'pupils.dat');
  reset (pupil_file);
  while not eof (pupil_file) do
    begin
      read (pupil_file, pupils[i]);
      inc (i);
    end;
  close (pupil_file);
end;

procedure find_data;
var name_to_find : string;
      i : integer;
      found : Boolean;
begin
  writeln ('Enter name of student, surname followed by first name eg Smith, Tom.');
  readln (name_to_find);
  retrieve_data;
  for i := 1 to max do
    if pupils[i].name = name_to_find then
      begin
        writeln ('Student found.');
        writeln ('Name: ', name_to_find);
        writeln ('Form: ', pupils[i].form);
        writeln ('Year of entry: ', pupils[i].year_of_entry);
        found := true
      end;
      if not found then writeln (name_to_find, ' not found');
end;

begin
  repeat
  writeln ('Enter choice from these options:');
  repeat
    writeln ('1. Enter pupil data');
    writeln ('2. Show data');
    writeln ('3. Sort data');
    writeln ('4. Save data on file');
    writeln ('5. Read data from file');
    writeln ('6. Find a record from the name');
    writeln ('7. Quit');
    readln (choice)
    if not choice in [1..7] then writeln ('Invalid character, try again');
  until choice in [1..7];
  case choice of 
    1: get_data;
    2: show_data;
    3: sort_data;
    4: save_data;
    5: retrieve_data;
    6: find_data;
    7: writeln;
  end;
  until choice = 7;
  readln (x);
end.

 

Back to questions