Marco - 1 year ago 197
Pascal Question

# Find the second highest value

I've wrote this Code to find out the second highest value in an Array:

``````var
i,
ZweitMax,
Max : integer;

begin
Max := -maxint;
ZweitMax := -maxint;

for i := 1 to FELDGROESSE do

if inFeld[i] > Max then
begin
ZweitMax := Max;
Max := inFeld[i];
end
else
if inFeld[i] > ZweitMax then
begin
ZweitMax := inFeld[i];
FeldZweitMax := ZweitMax;
end
end;
``````

Where is the Problem in this Code and why it don't print out the right value?
Information: The Code is part of a function FeldZweitMax

There are currently two places where you set `ZweitMax` but only one of them also affects the return code of the function, `FeldZweitMax`.

The first part of the `if` statement can be changed into:

``````if inFeld[i] > Max then
begin
ZweitMax := Max;
FeldZweitMax := ZweitMax;  (* add this line *)
Max := inFeld[i];
end
(* and so on *)
``````

so as to ensure the return value is updated correctly.

Alternatively, you can just set `ZweitMax` alone in both places and then set the return value at the end:

``````for i := 1 to FELDGROESSE do
begin
if inFeld[i] > Max then
begin
ZweitMax := Max;
Max := inFeld[i];
end
else
begin
if inFeld[i] > ZweitMax then
begin
ZweitMax := inFeld[i];
end
end
end;
FeldZweitMax := ZweitMax;
``````

I actually prefer the latter since the calculation and return of the value are separate matters.

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