a. Write a program to print the diagonal (left & right) elements of an N N matrix.
Answers
Solution:
The given problem is solved in Python.
def diagonals(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1:
print(matrix[i][j], end = ' ')
else:
print('', end = ' ')
print()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
diagonals(matrix)
Explanation:
In this program, we have to print the diagonal elements of a square matrix.
Let us create the main logic for solving this problem.
Consider a 3 x 3 matrix:
Now, let us write the location of the diagonal elements.
For the left diagonal, we see that the row-index of the element is equal to the column-index. By checking that, we get the elements at the main diagonal.
So, the first part of our program would be:
def diagonals(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if i == j:
print(matrix[i][j], end = ' ')
else:
print('', end = ' ') # prints additional space for better look
print() # prints a new line for the next row
Now, our first task is completed. Now we want to display the right diagonal. How will we do it?
If we sum up the row-index and column-index of the right diagonal elements, we get:
> 0 + 2 = 2
> 1 + 1 = 2
> 2 + 0 = 2
Which is one less than the number of rows in the matrix.
So, we find the second logic. If the sum of the row-index and column-index is one less than the number of rows, it is a diagonal element. We check that by adding an or operator.
So, the final cοde looks like:
def diagonals(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1:
print(matrix[i][j], end = ' ')
else:
print('', end = ' ') # prints additional space for better look
print() # prints a new line for the next row
Hence, our problem is solved.!!
Refer to the attachment for output.