Advertisement
luliu

Myprogramminglab 71018

Dec 2nd, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. /*
  2.  * Lu Liu
  3.  * 12/2/2015
  4.  * CSCI-111-D01
  5.  * Myprogramminglab 71018
  6.  * Sums all the numbers in the major diagonal
  7.  */
  8.  
  9. import java.util.Scanner;
  10. public class DiagonalSum{
  11.     public static void main(String args[]) {
  12.         Scanner sc = new Scanner(System.in);
  13.         System.out.println("Enter the dimension n of an n x n matrix : ");
  14.         int n = sc.nextInt();
  15.         double matrix[][] = new double[n][n];
  16.         System.out.println("\nEnter the matrix row by row ");
  17.         for (int i = 0; i < matrix.length; i++) {
  18.             for (int j = 0; j < matrix.length; j++) {
  19.                 matrix[i][j] = sc.nextDouble();
  20.             }
  21.         }
  22.         double diagonalSum = sumMajorDiagonal(matrix);
  23.         System.out.println("\nSum of the major diagonal of the matrix : " + diagonalSum);
  24.     }
  25.     public static double sumMajorDiagonal(double[][] m) {
  26.         double sum = 0;
  27.         for (int i = 0; i < m.length; i++) {
  28.             for (int j = 0; j < m.length; j++) {
  29.                 if (i == j)
  30.                 sum += m[i][j];
  31.             }
  32.         }
  33.         return sum;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement