# Java Program to Find the Trace of a Matrix

Write a Java program to find the trace of a matrix using for loop. The trace of a matrix is the sum of its diagonal. In this Java example, we use nested for loop to iterate matrix rows and columns. Next, if(i == j) checks whether it’s a diagonal element and adds that item to trace.

```package NumPrograms;

import java.util.Scanner;

public class MatrixTrace1 {

private static Scanner sc;

public static void main(String[] args) {

int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);

System.out.print("Enter Matrix Rows and Columns =  ");
rows = sc.nextInt();
columns = sc.nextInt();

int[][] Tra_arr = new int[rows][columns];

System.out.println("Please Enter the Matrix Items =  ");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
Tra_arr[i][j] = sc.nextInt();
}
}

for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
}
}

System.out.println("\nThe Trace Of the Matrix = " + trace);

}
}```

## Java program to find the trace of a matrix using a while loop

```package NumPrograms;

import java.util.Scanner;

public class MatrixTrace2 {
private static Scanner sc;
public static void main(String[] args) {

int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);

System.out.print("Enter Matrix Rows and Columns =  ");
rows = sc.nextInt();
columns = sc.nextInt();

int[][] Tra_arr = new int[rows][columns];

System.out.println("Please Enter the Matrix Items =  ");
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
Tra_arr[i][j] = sc.nextInt();
j++;
}
i++;
}

i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
j++;
}
i++;
}

System.out.println("\nThe Trace Of the Matrix = " + trace);

}
}```
``````Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =
10 20 30
40 50 60
70 80 125

The Trace Of the Matrix = 185``````

This Java example uses the do while loop to calculate and print the trace of a given matrix.

```package NumPrograms;

import java.util.Scanner;

public class MatrixTrace3 {
private static Scanner sc;
public static void main(String[] args) {

int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);

System.out.print("Enter Matrix Rows and Columns =  ");
rows = sc.nextInt();
columns = sc.nextInt();

int[][] Tra_arr = new int[rows][columns];

System.out.println("Please Enter the Matrix Items =  ");
i = 0;
do
{
j = 0;
do
{
Tra_arr[i][j] = sc.nextInt();
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
}while(++j < columns);
}while(++i < rows);

System.out.println("\nThe Trace Of the Matrix = " + trace);

}
}```
``````Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =
19 22 45
77 88 125
13 50 500

The Trace Of the Matrix = 607``````