Reputation: 55
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?
Upvotes: 1
Views: 835
Reputation: 21045
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
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.
Upvotes: 3