typestar

grade_report.pas in Delphi

Quiz scores for five students, averaged into letter grades with a class summary underneath.

program GradeReport;

uses SysUtils;

const
  Names: array[0..4] of string =
    ('Okafor', 'Lindqvist', 'Ramos', 'Chen', 'Baptiste');
  // One row of quiz scores per student, in the same order as Names.
  Scores: array[0..4, 0..2] of Integer =
    ((88, 92, 79),
     (71, 68, 80),
     (95, 99, 91),
     (58, 64, 72),
     (83, 77, 90));

// A case on the tens digit is tidier than four chained comparisons.
function LetterFor(Mean: Double): string;
begin
  case Trunc(Mean) div 10 of
    10, 9: Result := 'A';
    8: Result := 'B';
    7: Result := 'C';
    6: Result := 'D';
  else
    Result := 'F';
  end;
end;

var
  I, J, Total, Passing: Integer;
  Mean, ClassSum, Best: Double;
  TopName: string;
begin
  ClassSum := 0;
  Passing := 0;
  Best := 0;
  TopName := '';

  WriteLn(Format('%-10s %4s %4s %4s %7s  %s',
    ['student', 'q1', 'q2', 'q3', 'mean', 'grade']));
  WriteLn(StringOfChar('-', 41));

  for I := 0 to High(Names) do
  begin
    Total := 0;
    for J := 0 to High(Scores[I]) do
      Total := Total + Scores[I][J];
    Mean := Total / Length(Scores[I]);

    WriteLn(Format('%-10s %4d %4d %4d %7.1f  %s',
      [Names[I], Scores[I][0], Scores[I][1], Scores[I][2],
       Mean, LetterFor(Mean)]));

    ClassSum := ClassSum + Mean;
    if Mean >= 70 then
      Inc(Passing);
    if Mean > Best then
    begin
      Best := Mean;
      TopName := Names[I];
    end;
  end;

  WriteLn(StringOfChar('-', 41));
  WriteLn(Format('class mean %.1f, %d of %d passing',
    [ClassSum / Length(Names), Passing, Length(Names)]));
  WriteLn(Format('top of the class: %s at %.1f', [TopName, Best]));
end.

How it works

  1. Scores: array[0..4, 0..2] of Integer holds one row per student, in the same order as Names.
  2. LetterFor runs case Trunc(Mean) div 10 of over the tens digit, with else catching the rest.
  3. The widths in %-10s %4d %4d %4d %7.1f line the columns up and StringOfChar('-', 41) rules them.

Keywords and builtins used here

The run, in numbers

Lines
68
Characters to type
1445
Tokens
446
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 357 seconds.

Type this snippet

Step 2 of 3 in Encore, step 26 of 27 in Language basics.

← Previous Next →