The normal of a matrix is the square root of the sum of squares of all its elements, while the trace is the sum of the elements on its main diagonal.
- The normal can be calculated for any matrix, while the trace is defined only for a square matrix.
- For an (N \times N) matrix, both values can be calculated by traversing the matrix elements.
Examples
Input:
1 2 3
4 5 6
7 8 9Output:
Normal = 16.88
Trace = 15Explanation: The normal is:
\sqrt{1^2+2^2+3^2+4^2+5^2+6^2+7^2+8^2+9^2} = \sqrt{285} \approx 16.88 The trace is: 1+5+9=15

Approach
The normal is calculated by finding the sum of squares of all matrix elements and then taking its square root. The trace is calculated by adding the elements whose row and column indices are the same.
- Initialize variables to store the sum of squares and trace.
- Traverse every element of the matrix.
- Add the square of each element to the sum of squares.
- Add mat[i][i] to the trace when the row and column indices are the same.
- Take the square root of the sum of squares to obtain the normal.
- Print the normal and trace.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const int MAX = 100;
// Returns the normal of an N x N matrix
double findNormal(int mat[][MAX], int n)
{
long long sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum += 1LL * mat[i][j] * mat[i][j];
}
}
return sqrt(sum);
}
// Returns the trace of an N x N matrix
int findTrace(int mat[][MAX], int n)
{
int trace = 0;
for (int i = 0; i < n; i++) {
trace += mat[i][i];
}
return trace;
}
int main()
{
int mat[][MAX] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
double normal = findNormal(mat, 3);
int trace = findTrace(mat, 3);
cout << fixed << setprecision(2);
cout << "Normal = " << normal << endl;
cout << "Trace = " << trace << endl;
return 0;
}
Output
Normal = 16.88 Trace = 15
Explanation
- findNormal() traverses the complete matrix and adds the square of every element to sum.
- sqrt(sum) returns the normal of the matrix.
- findTrace() traverses only the main diagonal using mat[i][i].
- setprecision(2) displays the normal up to two decimal places.
- 1LL ensures that multiplication is performed using long long before adding to the sum.