Problem: Write a C++ program to print the left and right diagonals elements of a matrix (2-dimensional array).
A square matrix have two diagonals:
- 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.
So, to print diagonal elements of a matrix in C++:
- Loop from
i=0
toi< size
of the matrix. - Nest another for loop from
j=0
toi< size
of the matrix. - Check
if(i==j || i+j==SIZE-1)
. If yes then printmatrix[i][j]
else print whitespace. - End the loops.
Here is the C++ program that prints the diagonals elements of a matrix:
#include <iostream>
#define SIZE 5
using namespace std;
int main()
{
int matrix[SIZE][SIZE];
//Take input into Matrix
cout << "Enter elements into the matrix: \n";
for(int i=0; i<SIZE ; i++){
for(int j=0; j<SIZE; j++){
cin >> matrix[i][j];
}
}
//Output the diagonal elements
cout << "Diagonal Elements: \n";
for(int i=0; i<SIZE; i++){
for(int j=0; j<SIZE; j++){
if(i==j || i+j==SIZE-1)
cout << matrix[i][j] << "\t";
else
cout << " " << "\t";
}
cout << "\n";
}
return 0;
}
Output:
In the above program, we first take input from the user into the matrix, then using nested ‘for’ loops, 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++.