How to print the boundary elements of a matrix in Pascal

2 Answers

0 votes
program PrintMatrixBoundaries;

const
  COLS = 5;
  ROWS = 4;

type
  TIntMatrix = array[1..ROWS, 1..COLS] of Integer;

procedure PrintMatrixBoundaries(matrix: TIntMatrix; rows, cols: Integer);
var
  i, j: Integer;
begin
  for i := 1 to rows do
    for j := 1 to cols do
      if (i = 1) or (j = 1) or (i = rows) or (j = cols) then
        write(matrix[i, j], ' ');
end;

var
  matrix: TIntMatrix;
begin
  { Initialize the matrix }
  matrix[1,1] := 1;  matrix[1,2] := 2;  matrix[1,3] := 3;  matrix[1,4] := 4;  matrix[1,5] := 5;
  matrix[2,1] := 6;  matrix[2,2] := 7;  matrix[2,3] := 8;  matrix[2,4] := 9;  matrix[2,5] := 10;
  matrix[3,1] := 11; matrix[3,2] := 12; matrix[3,3] := 13; matrix[3,4] := 14; matrix[3,5] := 15;
  matrix[4,1] := 16; matrix[4,2] := 17; matrix[4,3] := 18; matrix[4,4] := 19; matrix[4,5] := 20;

  { Print boundary elements }
  PrintMatrixBoundaries(matrix, ROWS, COLS);
end.




(*
run:

1 2 3 4 5 6 10 11 15 16 17 18 19 20 

*)

 



answered Dec 15, 2025 by avibootz
0 votes
program MatrixBoundary;

const
  ROWS = 4;
  COLS = 5;

type
  TIntMatrix = array[1..ROWS, 1..COLS] of Integer;

procedure PrintMatrixBoundaries(matrix: TIntMatrix; rows, cols: Integer);
var
  i, j: Integer;
begin
  { Print first row }
  for j := 1 to cols do
    write(matrix[1, j], ' ');

  { Print last column }
  for i := 2 to rows do
    write(matrix[i, cols], ' ');

  { Print last row in reverse }
  for j := cols - 1 downto 1 do
    write(matrix[rows, j], ' ');

  { Print first column upwards }
  for i := rows - 1 downto 2 do
    write(matrix[i, 1], ' ');
end;

var
  matrix: TIntMatrix;
begin
  { Initialize the matrix }
  matrix[1,1] := 1;  matrix[1,2] := 2;  matrix[1,3] := 3;  matrix[1,4] := 4;  matrix[1,5] := 5;
  matrix[2,1] := 6;  matrix[2,2] := 7;  matrix[2,3] := 8;  matrix[2,4] := 9;  matrix[2,5] := 10;
  matrix[3,1] := 11; matrix[3,2] := 12; matrix[3,3] := 13; matrix[3,4] := 14; matrix[3,5] := 15;
  matrix[4,1] := 16; matrix[4,2] := 17; matrix[4,3] := 18; matrix[4,4] := 19; matrix[4,5] := 20;

  { Print boundary elements }
  PrintMatrixBoundaries(matrix, ROWS, COLS);
end.




(*
run:

1 2 3 4 5 10 15 20 19 18 17 16 11 6 

*)

 



answered Dec 15, 2025 by avibootz
...