java Write a method that sums all the numbers in the major
java - Write a method that sums all the numbers in the major diagonal in an n x n matrix of double values using the following header:
public static double sumMajorDiagonal(double [][] m)
Write a test program that first prompts the user to enter the dimension n of an n x n matrix, then asks them to enter the matrix row by row (with the elements separated by spaces). The program should then print out the sum of the major diagonal of the matrix.
SAMPLE RUN:
Enter dimension n of nxn matrix:Enter row·0:Enter row 1:Enter·row 2:Enter row 3:17.1
(can have 3 or 4 rows)
Solution
//DiagonalSum.java
import java.io.*;
import java.util.*;
class DiagonalSum
{
public static double sumMajorDiagonal(double[][] matrix)
{
double sum=0.0;
for(int i=0;i<matrix.length;i++)
sum=sum+matrix[i][i];
return sum;
}
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.print(\"Enter dimension n of nxn Matrix: \");
int n=scan.nextInt();
double matrix[][]=new double[n][n];
for(int i=0;i<n;i++)
{
System.out.print(\"Enter row \" + (i) + \": \");
for(int j=0;j<n;j++)
{
matrix[i][j]=scan.nextDouble();
}
}
System.out.println(\"\ Input Matrix:\");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(matrix[i][j]+\"\\t\");
}
System.out.println();
}
System.out.println(\"\ Sum of Major diagonal:\" + sumMajorDiagonal(matrix) );
}
}
/*
output:
Enter dimension n of nxn Matrix: 3
Enter row 0: 1 2 3
Enter row 1: 4 5 6
Enter row 2: 7 8 9
Input Matrix:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
Sum of Major diagonal:15.0
*/

