I have been trying to write this program since 9:00 am. and I am exhausted now. Could someone give a some direction???????

I am to write a program for a two dimensional (5 rols and 5 cols) and then write a procedure to rotate it 90 degrees. I wrote the matrix part but I can't get it to rotate .

thanks
Linda

Dani AI

Generated

Two simple ways to rotate a square 5x5 matrix in Pascal are: (1) write into a second matrix using an index mapping, or (2) do it in-place by transposing and then reversing rows. As hinted, a plain transpose is not enough for a 90-degree rotation — you must also reverse the order of elements (reverse rows for clockwise, reverse columns for counterclockwise). Below are compact Pascal examples for both approaches.

Type-and-copy approach (easy to read and test):

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

procedure Rotate90Clockwise(var A: TMatrix; N: Integer);
var
  B: TMatrix;
  i, j: Integer;
begin
  for i := 1 to N do
    for j := 1 to N do
      B[j, N - i + 1] := A[i, j];  // map (i,j) -> (j, N-i+1)
  for i := 1 to N do
    for j := 1 to N do
      A[i, j] := B[i, j];          // copy back (older Pascals may not allow A := B)
end;

In-place (no extra matrix) using transpose + reverse-rows:

procedure Rotate90ClockwiseInPlace(var A: TMatrix; N: Integer);
var
  i, j, tmp: Integer;
begin
  // transpose
  for i := 1 to N do
    for j := i + 1 to N do
    begin
      tmp := A[i, j]; A[i, j] := A[j, i]; A[j, i] := tmp;
    end;
  // reverse each row
  for i := 1 to N do
    for j := 1 to N div 2 do
    begin
      tmp := A[i, j]; A[i, j] := A[i, N - j + 1]; A[i, N - j + 1] := tmp;
    end;
end;

Troubleshooting notes: be consistent with index bounds (1..5 vs 0..4), pass the array with var to modify it, and decide clockwise vs counterclockwise (for counterclockwise use B[N - j + 1, i] := A[i, j] or reverse columns after transpose). Test with a matrix filled 1..25 so you can visually verify positions. These algorithms are O(N^2); the copy method uses O(N^2) extra memory while the in-place method uses O(1) extra memory. This expands on ’s transpose hint and fulfills ’s offer to finish code.

Recommended Answers

All 2 Replies

think carefully what is happening to the numbers in the matrix. I take it you are transposing the matrix, have you tried interchanging the rows and columns (ie the two dimensions of the array)?

if you post your code i will have a go at finishing it off for you.

--------------------------------------------------------------------------
NEW - FREE pc support using your Instant Messenger

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.