Question

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;
Was it helpful?

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;

OTHER TIPS

In addition to Howard's answer, set '0' to 'Highest' before beginning the loop. Being uninitialized, it is having an arbitrary value, probably higher then the highest score.

In addition to the accepted answer, make sure you turn on your warnings and hints, and you'll see:

      testhighest.pp(16,39) Warning: Local variable "Highest" does not seem to be initialized

which is the

        If TopScores[Count].Score > Highest Then

line

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top