0% found this document useful (0 votes)
14 views

Transpose A 2D Array

Transpose

Uploaded by

nailearivera45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Transpose A 2D Array

Transpose

Uploaded by

nailearivera45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

To swap rows and columns in a

two-dimensional array in Delphi, you can


create a procedure that transposes the
array in place. Below is the Delphi code
that demonstrates how to do this with a
single two-dimensional array:
```delphi
program SwapRowsAndColumns;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
Rows = 5;
Cols = 5;
var
arrNumbers: array[1..Rows, 1..Cols] of
Integer;
i, j: Integer;
procedure GenerateRandomNumbers;
var
firstNumber: Integer;
begin
Randomize; // Initialize random number
generator
// Generate numbers
for i := 1 to Rows do
begin
firstNumber := Random(71) + 10; //
Generates a number from 10 to 80
arrNumbers[i, 1] := firstNumber;
for j := 2 to Cols do
begin
arrNumbers[i, j] := Random(11) +
(firstNumber - 5); // Generates numbers
between firstNumber - 5 and firstNumber +
5
end;
end;
end;
procedure PrintArray;
begin
for i := 1 to Rows do
begin
for j := 1 to Cols do
begin
Write(arrNumbers[i, j]:4);
end;
Writeln;
end;
end;
procedure TransposeArray;
var
temp: Integer;
begin
for i := 1 to Rows do
begin
for j := i + 1 to Cols do
begin
if (i <= Cols) and (j <= Rows) then //
Ensure we don't go out of bounds
begin
// Swap elements
temp := arrNumbers[i, j];
arrNumbers[i, j] := arrNumbers[j, i];
arrNumbers[j, i] := temp;
end;
end;
end;
end;
begin
// Generate random numbers
GenerateRandomNumbers;
// Print original array
Writeln('Original Array:');
PrintArray;
// Transpose the array
TransposeArray;
// Print transposed array
Writeln('Transposed Array:');
PrintArray;
Readln; // Wait for user input before
closing
end.
```
### Explanation:
1. **GenerateRandomNumbers**: This
procedure populates the `arrNumbers`
array with random numbers according to
the previously defined logic.
2. **PrintArray**: This procedure prints the
contents of the array in a formatted
manner.
3. **TransposeArray**: This procedure
swaps the elements of the array to
transpose it. The loops go through the
upper triangle of the matrix and swap
elements `[i, j]` with `[j, i]`.
- The check `(i <= Cols) and (j <= Rows)`
ensures that we do not access
out-of-bounds indices when transposing.
4. **Main Program**: The program
generates random numbers, prints the
original array, transposes it, and then prints
the transposed array.
You can compile and run this code in a
Delphi environment to see how the rows
and columns are swapped in the 2D array.

You might also like