Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Lu Liu
- * 12/2/2015
- * CSCI-111-D01
- * Myprogramminglab 71018
- * Sums all the numbers in the major diagonal
- */
- import java.util.Scanner;
- public class DiagonalSum{
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the dimension n of an n x n matrix : ");
- int n = sc.nextInt();
- double matrix[][] = new double[n][n];
- System.out.println("\nEnter the matrix row by row ");
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- matrix[i][j] = sc.nextDouble();
- }
- }
- double diagonalSum = sumMajorDiagonal(matrix);
- System.out.println("\nSum of the major diagonal of the matrix : " + diagonalSum);
- }
- public static double sumMajorDiagonal(double[][] m) {
- double sum = 0;
- for (int i = 0; i < m.length; i++) {
- for (int j = 0; j < m.length; j++) {
- if (i == j)
- sum += m[i][j];
- }
- }
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement