How to find the median among three given numbers in Pascal

1 Answer

0 votes
program MedianOfThree;

{
  Function to compute the median of three integers.
  The median is the value that is neither the minimum nor the maximum.
  We compute:
      median = a + b + c - min(a,b,c) - max(a,b,c)
}
function MedianOfThreeNumbers(a, b, c: Integer): Integer;
var
  minVal, maxVal: Integer;
begin
  { Determine the minimum of the three numbers }
  minVal := a;
  if b < minVal then
    minVal := b;
  if c < minVal then
    minVal := c;

  { Determine the maximum of the three numbers }
  maxVal := a;
  if b > maxVal then
    maxVal := b;
  if c > maxVal then
    maxVal := c;

  { The median is the remaining value }
  MedianOfThreeNumbers := a + b + c - minVal - maxVal;
end;

begin
  { Test cases }
  Writeln('The median of [1, 1, 1] is ',
          MedianOfThreeNumbers(1, 1, 1));

  Writeln('The median of [10, 3, 7] is ',
          MedianOfThreeNumbers(10, 3, 7));

  Writeln('The median of [10, -10, -10] is ',
          MedianOfThreeNumbers(10, -10, -10));

  Writeln('The median of [3, 3, 5] is ',
          MedianOfThreeNumbers(3, 3, 5));
end.



(*
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10, -10, -10] is -10
The median of [3, 3, 5] is 3

*)

 



answered Mar 26 by avibootz
edited Mar 26 by avibootz
...