Marco Marco - 26 days ago 14
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 }

const
FELDGROESSE = 10;

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

var
Feld : tFeld;
i : integer;

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

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.

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


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

Answer

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.

Comments