Answer:
Following are the code to this question:
import java.util.*; //import package for user input
public class Main //defining main class
{
public static double sumMajorDiagonal(double [][] m) //defining method sumMajorDiagonal
{
double sum = 0; //defining double variable sum
int i, j; //defining integer variable
for(i = 0; i <m.length; i++) //defining loop to count row
{
for(j = 0; j < m.length; j++) //defining loop to count column
{
if(i == j) //defining condition to value of i is equal to j
{
sum=sum+ m[i][j]; //add diagonal value in sum variable
}
}
}
return sum; //return sum
}
public static void main(String args[]) //defining main method
{
int n,i,j; //defining integer variable
System.out.print("Enter the dimension value: "); //print message
Scanner ox = new Scanner(System.in); //creating Scanner class object for user input
n = Integer.parseInt(ox.nextLine()); //input value and convert value into integer
double m[][] = new double[n][n]; //defining 2D array
for(i = 0; i < m.length; i++)
{
String t = ox.nextLine(); // providing space value
String a[] = t.split(" "); // split value
for(j = 0; j < a.length; j++) //defining loop to count array value
{
double val = Double.parseDouble(a[j]); //store value in val variable
m[i][j] = val; //assign val in to array
}
}
double d_sum = sumMajorDiagonal(m); //call method store its return value in d_sum variable
System.out.println("diagonal matrix sum: "+ d_sum); //print sum
}
}
output:
Enter the dimension value: 3
1 2 3
1 2 3
1 2 4
diagonal matrix sum: 7.0
Step-by-step explanation:
Program description:
- In the given java language code, a method "sumMajorDiagonal" is declared, that accepts a double array "m" in its parameter, inside the method two integer variable "i and j" and one double variable "sum" is defined, in which variable i and j are used in a loop to count array value, and a condition is defined that checks its diagonal value and use sum variable to add its value and return its value.
- In the main method first, we create the scanner class object, that takes array elements value and passes into the method, then we declared a double variable d_sum that calls the above static method, that is "sumMajorDiagonal" and print its return value with the message.