Program to Find Normal and Trace of a Matrix in Java using For loop
ADVERTISEMENTS
Program to find normal and trace of a matrix in java using for loop. In this article, you will learn how to make program to find normal and trace of a matrix in java using for loop.
What is the Normal of a square matrix?
The square root of the sum of the squares of each element of the matrix.
What is the Trace of a square matrix?
The sum of the diagonal elements of the square matrix.
Source Code
// Program to Find Normal and Trace of a Matrix in Java using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i, j, n, sum = 0, a = 0;
double sum1 = 0, normal;
System.out.println ("Enter the number of rows[columns] of the matrix::\n");
n = in.nextInt();
int x[][];
x = new int[n][n];
System.out.println ("\n----Enter the " + n * n + " elements of the first matrix----\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
x[i][j] = in.nextInt();
a = x[i][j] * x[i][j];
sum1 += a;
}
}
normal = (double) Math.sqrt(sum1);
System.out.println ("\n\nThe normal of the given matrix is: " + normal);
for(i = 0; i < n; i++) {
sum = sum + x[i][i];
}
System.out.println ("\nThe Trace of the given matrix is: " + sum + "\n");
}
}
Output
Enter the number of rows[columns] of the matrix::
4
----Enter the 16 elements of the first matrix----
43 1 5 65 23 65 76 34 76 4 76 87 4 43 56 2
The normal of the given matrix is: 204.76327795774318
The Trace of the given matrix is: 186