• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
October 26, 2022 |670 Views
C++ Program to convert the diagonal elements of the matrix to 0
Description
Discussion

In this video, we will write a C++ Program to convert the diagonal elements of the matrix to 0.

Diagonal Elements in Matrix: An element on the main diagonal of a square matrix, that is, an element in row k and column k where k is an integer between 1 and the number of rows (or columns) in the matrix.

Example: 
Input: mat[][] = 
{{ 2, 1, 7 },
{ 3, 7, 2 },
{ 5, 4, 9 }}
Output: 
{ {0, 1, 0},
{3, 0, 2},
{0, 4, 0}}

Algorithm:
Step 1: Take an input matrix.

Step 2: Traverse a matrix and check if the diagonal matrix elements are equal to zero or not.
if ((i == j ) || (i + j + 1) == n) 
mat[i][j] = 0 

Step 3: Print a matrix.

Here we see 2 different methods for converting the diagonal elements of the matrix to 0:

1) Using Loop: In the first method, we run two loops i.e. outer loop which is used for no. of rows, and the inner loop for no. of columns. Now Check check the condition:
if ((i == j ) || (i + j + 1) == n) 
Then matrix element becomes 0 i.e mat[i][j] = 0 . At last, we print a complete matrix.

Time Complexity: O(m*n)
Space complexity: O(1)

2) Using Square matrix: In this method, we use a square matrix. So we directly traverse diagonal elements of a matrix using a loop and convert them into zero if they are non-zero elements. 

Time Complexity: O(n)
Space complexity: O(1)