Summary: In this programming example, we will learn to write a C++ program to print the diagonals (left and right) of a matrix (2D array).

A square matrix has two diagonals with the following properties:

  • Left Diagonal – The row and column indexes of a left diagonal element are equal i.e. i==j.
  • Right Diagonal – The sum of the row and column indexes of a right diagonal element is always one less than the size (order) of the matrix i.e. i+j==size-1.

We can use these properties to identify and output the diagonal elements of a matrix.

Steps to print diagonal elements of a matrix in C++:

  1. Loop from i=0 to i< size of the matrix.
  2. Nest another for loop from j=0 to i< size of the matrix.
  3. Check if(i==j || i+j==SIZE-1). If yes then print matrix[i][j] else print whitespace.
  4. End the loops.

Here is the implementation of the steps in C++:

Output:

Diagonal element of the matrix

In the above program, we first take input from the user into the 2d array i.e. matrix, then in another nested loop we output only those elements which satisfy any of the diagonal properties i.e. i==j or i+j<size-1.

Related Post: How to Find the Sum of Diagonal Elements of a Matrix?

In this tutorial, we learned the properties of diagonal elements of a square matrix and how to output the diagonal elements of a matrix in C++.

Leave a Reply