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,907 questions

51,839 answers

573 users

How to rotate a square matrix 90 degrees to the left in Pascal

1 Answer

0 votes
program RotateMatrixLeft;

const
  N = 3;  // Size of the square matrix

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

// Prints the matrix to the console
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;

// Rotates a square matrix 90 degrees to the left (counterclockwise)
// param matrix - The square matrix to rotate
procedure RotateMatrix90DegreesLeft(var matrix: TMatrix);
var
  layer, i, offset: Integer;
  first, last: Integer;
  top: Integer;
begin
  // Perform the rotation in-place
  for layer := 1 to N div 2 do
  begin
    first := layer;
    last := N - layer + 1;

    for i := first to last - 1 do
    begin
      offset := i - first;

      // Save the top element
      top := matrix[first, i];

      // Move right to top
      matrix[first, i] := matrix[i, last];

      // Move bottom to right
      matrix[i, last] := matrix[last, last - offset];

      // Move left to bottom
      matrix[last, last - offset] := matrix[last - offset, first];

      // Move top to left
      matrix[last - offset, first] := top;
    end;
  end;
end;

var
  matrix: TMatrix;

begin
  // Initialize the matrix
  matrix[1,1] := 1; matrix[1,2] := 2; matrix[1,3] := 3;
  matrix[2,1] := 4; matrix[2,2] := 5; matrix[2,3] := 6;
  matrix[3,1] := 7; matrix[3,2] := 8; matrix[3,3] := 9;

  RotateMatrix90DegreesLeft(matrix);

  Writeln('Matrix After 90 degrees Left Rotation:');
  PrintMatrix(matrix);
end.



(*
run:

Matrix After 90 degrees Left Rotation:
3 6 9 
2 5 8 
1 4 7 

*)

 



answered Oct 6, 2025 by avibootz
...