Java program to find trace of a matrix code example
Example: Java program to find trace of a matrix
import java.util.Scanner;
public class TraceMatrixDemo
{
public static void main(String[] args)
{
int[][] arrInput = new int[10][10];
int a, b;
double total = 0;
System.out.println("Please enter total rows and columns: ");
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int column = sc.nextInt();
System.out.println("Please enter matrix: ");
for(a = 0; a < row; a++)
{
for(b = 0; b < column; b++)
{
arrInput[a][b] = sc.nextInt();
System.out.print(" ");
}
}
System.out.println("Entered matrix is: ");
for(a = 0; a < row; a++)
{
for(b = 0; b < column; b++)
{
System.out.println(arrInput[a][b] + " ");
}
System.out.println(" ");
}
System.out.println("Trace of a matrix: ");
for(a = 0; a < row; a++)
{
for(b = 0; b < column; b++)
{
if(a == b)
{
total = total + (arrInput[a][b]);
}
}
}
System.out.println(total);
sc.close();
}
}