pTutorial

New way to learn Programming

Print Diagonal Matrix Java

Java example to print or access the diagonal element of the matrix (two dimensional array in java) and also calculate the sum of diagonal element of matrix.

Print Diagonal Matrix Java Example

public class PrintDiagonalMatrix {
    public static void main(String[] args ){   
    int sum=0;
    int a3[][]={{1,2,3,4},{10,20,30,40},{100,200,300,40},{1,2,0,4}};
    for(int j=0;j<a3.length;j++){
    System.out.println(a3[j][j]);
  }
    
}
}

Output

1
20
300
4

Print Diagonal Matrix Java

class SumOfDiagonalElement {
public static void main(String[] args ){   
    int sum=0;
    int a3[][]={{1,2,3,4},{10,20,30,40},{100,200,300,40},{1,2,0,4}};
    for(int j=0;j<a3.length;j++){
        sum+=a3[j][j];
    }
    System.out.println("Sum of Diagonal Of Matrix="+sum);
}

}

Output

Sum of Diagonal Of Matrix=325

See Also


QUOTES OF THE DAY

The basis of all progress is self-reliance

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER