Pascal: Sort an Array of Pupil Records

program sorting_pupils;
const max = 5;
type pupil_record = record
          name : string;
          form : string;
          year_of_entry: integer;
        end;
        pupil_array = array [1..max] of pupil_record;

var   pupils : pupil_array;

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;

begin
  get_data;
  show_data;
  readln;
end.

Here is some code to print the records (add 'printers' to uses section):

procedure print_data;
var i, x, y: integer;
begin
  printer.begindoc;
  x:=150; y:=150;
//set default print start position
  printer.canvas.font.size:=12;
  writeln ('You entered:');
  for i:= 1 to max do
    with pupils[i] do
      begin
  
      printer.canvas.textout(x, y, name);
x:=x+ 500;
//experiment with values
      printer.canvas.textout(x,y, form);
x:=x+ 500;
//experiment with values
printer.canvas.textout(x,y, inttostr( year_of_entry)); //have to convert integer to string for display
x:=150;
//back to default x position for next line
y:=y+150;
//increment y for next line down
end;
printer.enddoc;
end;

And we can change the main program section to include a menu:

begin
repeat
writeln('Five Pupil Records. Choose an option');
writeln('1. Get data');
writeln('2. Sort data');
writeln('3. Display data');
writeln('4. Print data');
writeln('5. Quit');
readln(choice);
case choice of
'1': get_data;
'2': sort_data;
'3': show_data;
'4': print_data;
end;
until not (choice in['1'..'4']);
end.

Back to questions