Search code examples
pascalcounterrecordrecordshighest

Finding highest value from a record


I'm trying to code a procedure which goes through a record of numbers and finds which one is highest, the code currently is below. The issue I have is that it just seems to list the last score on the record (not the highest). Any help is greatly appreciated.

Procedure FindTopScore(Var TopScores : TTopScores);
Var
Count : Integer;
Highest : Integer;
Name: String;

Begin
     For Count := 1 to MaxSize Do
          If TopScores[Count].Score > Highest Then
     Highest := TopScores[Count].Score;
     Name := TopScores[Count].Name;
       Writeln('Higest score is by ' ,TopScores[Count].Name, ' of ', TopScores[Count].Score);
End;

Solution

  • You're not outputting Highest, but TopScores[Count].Score. Just use

     Writeln('Highest is ', Highest, ' for ', Name);
    

    Also you should put the name into a variable Name inside the if-statement (it actually is outside).

    Addon: If you want all names in case of a tie you can use e.g. the following code

    Highest := 0;
    For Count := 1 to MaxSize Do Begin
         If TopScores[Count].Score = Highest Then Begin
             Name := Name + ' and ' + TopScores[Count].Name;
         End;
         If TopScores[Count].Score > Highest Then Begin
             Highest := TopScores[Count].Score;
             Name := TopScores[Count].Name;
         End;
     End;