A square matrix contains two diagonals. Here the program is written to exchange one diagonal with another.
Normally for exchanging two elements a and b where the value of a=5 and b=6 we use the following steps:
t=a [t=5]
a=b [a=6]
b=t [b=5]
where ‘t’ is a temporary variable to store the value temporarily for exchanging. This simple technique is used here to exchange the elements of two diagonals.
After exchanging the value of a=6 and b=5. The values are interchanged.
For example:
This is a 3×3 matrix i.e. the matrix contains 3 rows and 3 columns.
Now, we want to exchange two diagonals:
For this first the first element (here, 10) of the principal diagonal is stored in the temporary variable. Then last element (30) of that row i.e. the first element of the 2nd diagonal (with which the principal diagonal is to be exchanged) is stored in the position of ‘10’ making the matrix:
Now, the value of the temporary element will be stored at the position of ‘30’ (the previous position). Hence the matrix will be:
That means the first elements are exchanged with each other. Similarly, the other elements of the diagonals will also be exchanged and will get the new matrix as:
INPUT: A matrix
OUTPUT: The matrix after exchanging the diagonals.
PROCESS:
Step 1: [Taking the inputs]
Read m, n [The number of rows & columns of the matrix]
Step 2: [Exchanging the diagonals]
If m=n then
[Taking the elements of the matrix]
for i=0 to m-1 repeat
for j=0 to n-1 repeat
read a[i][j]
[End of ‘for’ loop]
[End of ‘for’ loop]
[interchanging the diagonals]
For i = 0 to m-1 repeat
Set t<-a[i][i]
Set a[i][i]<-a[i][m - i - 1]
Set a[i][m - i - 1]<-t
[End of ‘for’ loop]
[printing the matrix after interchanging the diagonals]
Print "The matrix after interchanging the diagonals is:"
for i = 0 to m-1 repeat
for j = 0 to n-1 repeat
print a[i][j]
[End of ‘for’ loop]
Move to the next line
[End of ‘for’ loop]
else
print "The given order is not square matrix"
[End of ‘if’]
Step 3: Stop.
TIME COMPLEXITY:
for(i = 0; i < m; ++i)--------------- O(m)
{ t=a[i][i];
a[i][i]=a[i][m - i - 1];
a[i][m - i - 1]=t;
}
The time complexity is O(m).
Related
Contributed by