- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find trace of matrix formed by adding Row-major and Column-major order of same matrix in C++ Program
In this tutorial, we are going to write a program that finds trace of matrix formed by row and column major matrices.
Let's see how to form a row and column major matrices when order of the matrix is given.
Order − 3 x 3
Row Major Matrix −
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
Column Major Matrix −
1 | 4 | 7 |
2 | 5 | 8 |
3 | 6 | 9 |
We have row and column major matrices. Now, we have to add both the matrices. And the trace of the resultant matrix is the result that we are looking for.
Let's see write the code to solve the problem. We have to complete the following 4 steps to finish the solution for the problem.
Create the row-major matrix.
Create the column-major matrix.
Add the both matrices and store the resultant matrix.
Find the trace of the resultant matrix and print the result.
Example
Let's see the code.
#include <iostream> #include <bits/stdc++.h> #include <regex> using namespace std; int traceOfRowAndColumnMajorMatrices(int m, int n) { int row_major[m][n], column_major[m][n], addition_result[m][n], count = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { row_major[i][j] = count; count += 1; } } count = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { column_major[j][i] = count; count += 1; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { addition_result[j][i] = row_major[i][j] + column_major[i][j]; } } int trace = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == j) { trace += addition_result[i][j]; } } } return trace; } int main() { int m = 3, n = 3; cout << traceOfRowAndColumnMajorMatrices(m, n) << endl; return 0; }
Output
If you execute the above program, then you will get the following result.
30
Conclusion
If you have any queries in the tutorial, mention them in the comment section.