
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Row-wise Common Elements in Two Diagonals of a Square Matrix in C++
Given a 2D square matrix as input. The goal is to find the elements that are common in both its primary and secondary diagonals. If the input matrix is
1 2 3 2 2 4 1 4 7
Then its primary diagonal is 1 2 7 and the secondary diagonal is 3 2 1. Common element is 2.
There will always be at least one common element in both.
Examples
Input − Matrix[][5] = {{1, 2, 1}, {4, 1, 6}, {1, 8, 1}};
Output − Row-wise common elements in diagonals:3
Explanation − The matrix is:
1 2 1 4 1 6 1 8 1
Primary diagonal=1 1 1, Secondary diagonal= 1 1 1
All 3 values are common. count=3
Input − Matrix[][5] = {{1, 4, 4, 1}, {3, 4, 4, 6}, {1, 1, 1, 4}, {1, 9, 9, 2}};
Output − Row-wise common elements in diagonals:3
Explanation − The matrix is:
1 4 4 1 3 4 4 6 1 1 1 4 1 9 9 2
Primary diagonal=1 4 1 2, Secondary diagonal= 1 4 1 1
First 3 values are common. count=3
Approach used in the below program is as follows
In this approach we will first traverse the square matrix row-wise from row 0. For each row check if element M[ i ][ i ] is equal to M[ i ][ size-i-1 ]. If yes then its common element of both diagonals, increment count.
Take the input matrix Matrix[][5].
Set its size.
Function countElement(int mt[][5], int size) takes the input matrix and its size and returns the count of common values in both primary and secondary diagonals.
Take the initial count as 0.
Traverse using for loop from i=0 to i
If mt[i][i] == mt[i][size-i-1] then increment count.
At the end return count as result.
Print the result in main.
Example
#include <iostream> using namespace std; int countElement(int mt[][5], int size){ int count = 0; for (int i=0;i<size;i++){ if (mt[i][i] == mt[i][size-i-1]){ count=count+1; } } return count; } int main(){ int Matrix[][5] = {{1, 2, 1}, {4, 1, 6}, {1, 8, 1}}; int size=3; cout<<"Row-wise common elements in diagonals:"<<countElement(Matrix, size); return 0; }
Output
If we run the above code it will generate the following Output
Row-wise common elements in diagonals:3