## Monday, 12 January 2015

### Java Program to calculate trace of a given matrix

This is a Java Program which calculates the trace of a matrix.

Generally trace of a square matrix is calculated as the sum of all the diagonal elements in a matrix.

PROGRAM :
```package codingcorner.in;

import java.util.Scanner;

public class Trace {
public static void main(String[] args) {
int rows, columns, i, j, trace = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter order of matrix :  \t");
rows = scan.nextInt();
columns = scan.nextInt();
int matrix[][] = new int[rows][columns];
System.out.print("Enter elements of the matrix :\n");
for (i = 0; i &lt; rows; i++) {
for (j = 0; j &lt; columns; j++) {
System.out.print("Enter element m" + (i + 1) + (j + 1) + ":\t");
matrix[i][j] = scan.nextInt();
}
}
scan.close();
System.out.print("\n\nMATRIX is :\n");
for (i = 0; i &lt; rows; i++) {
for (j = 0; j &lt; columns; j++)
System.out.print(matrix[i][j] + "\t");

System.out.print("\n");
}
System.out.print("\nIts TRACE is :\t");
for (i = 0; i &lt; rows; i++) {
for (j = 0; j &lt; columns; j++) {
if (i == j)
trace = trace + matrix[i][j];

}
}
System.out.print(trace);
}
}
```
OUTPUT : Java - Trace of a matrix