How to rotate a matrix 90 degrees clockwise in Pascal

2 Answers

0 votes
program RotateMatrix90;

const
  N = 3; // Matrix size

type
  TMatrix = array[1..N, 1..N] of Integer;

procedure Rotate90Clockwise(var matrix: TMatrix);
var
  i, j, temp: Integer;
begin
  // Step 1: Transpose the matrix
  for i := 1 to N do
    for j := i to N do
    begin
      temp := matrix[i, j];
      matrix[i, j] := matrix[j, i];
      matrix[j, i] := temp;
    end;

  // Step 2: Reverse each row
  for i := 1 to N do
    for j := 1 to N div 2 do
    begin
      temp := matrix[i, j];
      matrix[i, j] := matrix[i, N - j + 1];
      matrix[i, N - j + 1] := temp;
    end;
end;

// Function to print the matrix
procedure PrintMatrix(matrix: TMatrix);
var
  i, j: Integer;
begin
  for i := 1 to N do
  begin
    for j := 1 to N do
      Write(matrix[i, j], ' ');
    Writeln;
  end;
end;

var
  matrix: TMatrix = (
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)
  );

begin
  Writeln('Original Matrix:');
  PrintMatrix(matrix);

  Rotate90Clockwise(matrix);

  Writeln;
  Writeln('Rotated Matrix:');
  PrintMatrix(matrix);
end.


  
    
(*
run:

Original Matrix:
1 2 3 
4 5 6 
7 8 9 

Rotated Matrix:
7 4 1 
8 5 2 
9 6 3 
    
*)

 



answered May 29, 2025 by avibootz
0 votes
program RotateMatrix90;
 
const
  ROWS = 3; // Original matrix rows
  COLS = 4; // Original matrix columns
 
type
  TMatrix = array[1..ROWS, 1..COLS] of Integer;
  TRotatedMatrix = array[1..COLS, 1..ROWS] of Integer;
 
procedure Rotate90Clockwise(const matrix: TMatrix; var rotated: TRotatedMatrix);
var
  i, j, rows, cols: Integer;
begin
  rows := Length(matrix);    // Number of rows
  cols := Length(matrix[0]); // Number of columns
  
  for i := 1 to rows do
    for j := 1 to cols do
      rotated[j, rows - i + 1] := matrix[i, j]; // Mapping to rotated position
end;
 
// Function to print a matrix
procedure PrintMatrix(rows, cols: Integer; matrix: TRotatedMatrix);
var
  i, j: Integer;
begin
  for i := 1 to rows do
  begin
    for j := 1 to cols do
      Write(matrix[i, j], ' ');
    Writeln;
  end;
end;
 
var
  matrix: TMatrix = (
    (1, 2, 3, 4),
    (5, 6, 7, 8),
    (9, 10, 11, 12)
  );
  rotated: TRotatedMatrix;
 
begin
  Writeln('Original Matrix:');
  PrintMatrix(ROWS, COLS, TRotatedMatrix(matrix)); // Casting for printing
 
  Rotate90Clockwise(matrix, rotated);
 
  Writeln;
  Writeln('Rotated Matrix:');
  PrintMatrix(COLS, ROWS, rotated);
end.
 
   
     
(*
run:
 
Original Matrix:
1 2 3 4 
4 5 6 7 
7 8 9 10 
 
Rotated Matrix:
9 5 1 
10 6 2 
11 7 3 
12 8 4 
     
*)

 



answered May 29, 2025 by avibootz
edited May 29, 2025 by avibootz

Related questions

2 answers 183 views
2 answers 208 views
2 answers 238 views
2 answers 182 views
2 answers 167 views
...