Program to convert given Matrix to a Diagonal Matrix in C++

C++Server Side ProgrammingProgramming

Given with the matrix of size nxn the task it to convert any type of given matrix to a diagonal matrix.

What is a diagonal Matrix

Diagonal matrix is the nxn matrix whose all the non-diagonal elements are zero and diagonal elements can be any value.

Given below is the diagram of converting non-diagonal elements to 0.

$$\begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6 \\7 & 8 & 9 \end{bmatrix}\:\rightarrow\:\begin{bmatrix}1 & 0 & 3 \\0 & 5 & 0 \\7 & 0 & 9 \end{bmatrix}$$

The approach is to start one loop for all non-diagonal elements and another loop for diagonal elements and replace the value of non-diagonals with zero and leave diagonals elements unchanged.

Example

Input-: matrix[3][3] = {{ 1, 2, 3 },
   { 4, 5, 6 },
   { 7, 8, 9 }}
Output-: {{ 1, 0, 3},
   { 0, 5, 0},
   { 7, 0, 9}}
Input-: matrix[3][3] = {{ 91, 32, 23 },
   { 40, 51, 26 },
   { 72, 81, 93 }}
Output-: {{ 91, 0, 23},
   { 0, 51, 0},
   { 72, 0, 93}}

ALGORITHM

Start
Step 1-> define macro for matrix size as const int n = 10
Step 2-> Declare function for converting to diagonal matrix
   void diagonal(int arr[][n], int a, int m)
      Loop For int i = 0 i < a i++
         Loop For int j = 0 j < m j++
            IF i != j & i + j + 1 != a
               Set arr[i][j] = 0
            End
         End
      End
      Loop For int i = 0 i < a i++
         Loop For int j = 0 j < m j++
            Print arr[i][j]
         End
         Print \n
      End
Step 2-> In main()
   Declare matrix as int arr[][n] = { { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 } }
   Call function as diagonal(arr, 3, 3)
Stop

Example

 Live Demo

#include <iostream>
using namespace std;
const int n = 10;
//print 0 at diagonals in matrix of nxn
void diagonal(int arr[][n], int a, int m) {
   for (int i = 0; i < a; i++) {
      for (int j = 0; j < m; j++) {
         if (i != j && i + j + 1 != a)
         arr[i][j] = 0;
      }
   }
   for (int i = 0; i < a; i++) {
      for (int j = 0; j < m; j++) {
         cout << arr[i][j] << " ";
      }
      cout << endl;
   }
}
int main() {
   int arr[][n] = { { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 } };
   diagonal(arr, 3, 3);
   return 0;
}

Output

IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT

0 2 0
4 0 6
0 8 0
raja
Published on 18-Oct-2019 11:11:45
Advertisements