Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to find the second largest number in int array with Pascal

2 Answers

0 votes
program SecondLargestNumber;

var
  arr: array[0..9] of integer = (3, 14, 4, 1, 5, 90, 2, 6, 85, 7);
  size, i, largest, secondLargest: integer;

begin
    size := length(arr);

    if size < 2 then
    begin
        writeln('Array should have at least two elements.');
        exit;
    end;
    
    largest := arr[1];
    secondLargest := -MaxInt;

    for i := 2 to size do
    begin
        if arr[i] > largest then
        begin
            secondLargest := largest;
            largest := arr[i];
        end
        else if (arr[i] > secondLargest) and (arr[i] <> largest) then
            begin
                secondLargest := arr[i];
            end;
    end;

  if secondLargest = -MaxInt then
    writeln('There is no second largest element.')
  else
    writeln('The second largest element is: ', secondLargest);
end.



(*
run:

The second largest element is: 85

*)

 



answered Jan 19, 2025 by avibootz
0 votes
program SecondLargestNumber;

var
  arr: array[1..10] of integer;
  i, largest, secondLargest: integer;

begin
  { Initialize the array with some values }
  arr[1] := 34; arr[2] := 23; arr[3] := 45; arr[4] := 12; arr[5] := 77;
  arr[6] := 89; arr[7] := 78; arr[8] := 56; arr[9] := 90; arr[10] := 13;

  { Initialize largest and secondLargest }
  largest := -MaxInt;
  secondLargest := -MaxInt;

  { Iterate through the array to find the largest and second largest numbers }
  for i := 1 to 10 do
  begin
    if arr[i] > largest then
    begin
      secondLargest := largest;
      largest := arr[i];
    end
    else if (arr[i] > secondLargest) and (arr[i] <> largest) then
    begin
      secondLargest := arr[i];
    end;
  end;

  writeln('The second largest number in the array is: ', secondLargest);
end.



(*
run:

The second largest number in the array is: 89

*)

 



answered Apr 22, 2025 by avibootz
...