121. JAVA Program to find Trace of the given matrix.
How does this program work?
- In this program we are going to learn about how to find Trace of the given matrix using java.
- Trace of the matrix means sum of diagonal elements of the given matrix.
- And then by using the formula we can find the trace of a matrix.
Here is the code
//To find Trace of the given matrix
import java.util.Scanner;public class trace
{
public static void main(String[] args )
{
int rows, columns, i, j, trace = 0;
System.out.print("Enter rows and columns of matrix : \t");
Scanner obj = new Scanner(System.in );
rows = obj.nextInt();
columns = obj.nextInt();
int matrix[][] = new int[rows][columns];
System.out.print("Enter elements of the matrix :\n");
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < columns; j++ )
{
System.out.print("Enter element m" + (i) + (j) + ":\t");
matrix[i][j] = obj.nextInt();
}
}
obj.close();
System.out.print("\n\nMATRIX is :\n" );
for(i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
System.out.print(matrix[i][j] + "\t" );
System.out.print("\n");
}
System.out.print("\n TRACE of a matrix is :\t");
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < columns; j++ )
{
if ( i == j )
trace = trace + matrix [ i ][ j ];
}
}
System.out.print(trace );
}
}