Java Program to Find the Normal and Trace of a Matrix
In Java, when we work with matrices, there are two main concepts, and these concepts are Trace and Normal of a matrix. In this article, we will learn how to calculate them and discuss how to implement them in code. Before moving further, let's first understand what a matrix is.
What is a Matrix?
A matrix is a two-dimensional array that is arranged in rows and columns.
Example:
1 4 4
2 3 7
0 5 1
Note: This is a 3 x 3 matrix because it has 3 rows and 3 columns.
What is the Trace of a Matrix?
The Trace of a square matrix is the total we get when we add up all the numbers on the main diagonal.
Note: The main diagonal runs from the top-left corner to the bottom-right corner of the matrix.
What is the Normal of a Matrix?
The Normal of a matrix is the square root of the sum of the squares of all the numbers in the matrix. The image below shows how to calculate the Trace and Normal of a matrix.

How to Find Trace and Normal in Java?
Now, we are going to discuss how to calculate the Trace and Normal. We will write a program that takes a square matrix as input and then we will calculate its Trace and its Normal.
Example:
Input : matrix[][] = {{1, 4, 4},
{2, 3, 7},
{0, 5, 1}};Output : Normal = 11
Trace = 5
Explanation :
Normal = sqrt(1*1+ 4*4 + 4*4 + 2*2 + 3*3 + 7*7 + 0*0 + 5*5 + 1*1) = 11
Trace = 1+3+1 = 5
Input : matrix[][] = {{8, 9, 11},
{0, 1, 15},
{4, 10, -7}};
Output : Normal = 25
Trace = 2
Explanation :
Normal = sqrt(8*8 +9*9 + 11*11 + 0*0 + 1*1 + 15*15 + 4*4 + 10*10 + -7*-7) = 25
Trace = (8+1-7) = 2
Program to Find the Normal and Trace of a Matrix in Java
// Java program to find the trace
// and normal of the given matrix
public class Geeks {
// Method to calculate the Normal of the matrix
static int normal(int[][] matrix, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// square and add
sum += matrix[i][j] * matrix[i][j];
}
}
// square root of sum
return (int) Math.sqrt(sum);
}
// Method to calculate the Trace of the matrix
static int trace(int[][] matrix, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
// add diagonal elements
sum += matrix[i][i];
}
return sum;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 4, 4},
{2, 3, 7},
{0, 5, 1}
};
int size = matrix.length;
System.out.println("Trace of the Matrix is: "
+ trace(matrix, size));
System.out.println("Normal of the Matrix is: "
+ normal(matrix, size));
}
}
Output
Trace of the Matrix is: 5 Normal of the Matrix is: 11
Complexity of the above Program:
- Time Complexity: O(N*N), as we are using nested loops for traversing the matrix.
- Auxiliary Space: O(1), as we are not using any extra space.