Marco Marco - 1 year ago 125
Pascal Question

How to find the second largest value with Pascal

I have a Problem to Show the second largest value.

Here is the Code

program testeFeldZweitMax (input, output);
{ testet die Funktion FeldZweitMax }


tIndex = 1..FELDGROESSE;
tFeld = array [tIndex] of integer;

Feld : tFeld;
i : integer;

function FeldZweitMax (var inFeld : tFeld) : integer;
Maximum: integer;
j : tIndex;
Maximum := inFeld[1];
for j := 2 to FELDGROESSE do
if inFeld[j] > Maximum then
Maximum := inFeld[j];
FeldZweitMax := Maximum

begin { Testprogramm }
writeln('Bitte geben Sie ', FELDGROESSE, ' Zahlen ein:');
for i := 1 to FELDGROESSE do
read (Feld [i]);
writeln('Die zweitgroesste Zahl ist ', FeldZweitMax (Feld), '.');
end. { testeFeldZweitMax }

As you can see the Code Show me only the largest value. I Need some help with showing the second largest value.

Maximum, ZweitMax: integer;
j : tIndex;
Maximum := inFeld[1];
ZweitMax := inFeld[2];
for j := 1 to FELDGROESSE do
if inFeld[j] < Maximum then
inFeld[j] := Maximum;
Maximum := ZweitMax;
ZweitMax := inFeld[j];
FeldZweitMax := ZweitMax

It doesn't work perfectly. Some suggestions for me?

Answer Source

Consider that you have (at some point) the values Maximum > ZweitMax (f.ex. 5 and 2 respectively). The next value (x) to evaluate might be

  • a) x > Maximum
  • b) x > ZweitMax (but less than Maximum)
  • c) x < ZweitMax

In case a) Maximum should become x and ZweitMax should become previous Maximum

In case b) Maximum should remain and ZweitMax should become x

In case c) no change to Maximum and ZweitMax (IOW, no action required)

A couple of hints:

  • Initialize both Maximum and ZweitMax to the smallest possible value (according to the type) before you start to evaluate the actual inputted values.

  • In case a) set ZweitMax to previous Maximum before assigning the new value to Maximum.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download