Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use Java for the following: 1) Write a method that sums all the numbers in the m

ID: 663604 • Letter: U

Question

Use Java for the following:

1) 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.

2) Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:

0 0 0 1 0 1 1 1 0
0 1 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0 1

Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:

000010000 101001100 110100001

There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.

Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.

Explanation / Answer

public static void main(String[] args) {

            Scanner input = new Scanner(System.in);
            Scanner size = new Scanner(System.in);
       int n;

            double[][] m = new double[50][50];
       System.out.println("Enter the value of n for nxn matrix: ");
`       n = size.nextInt();
          

            System.out.println("Enter matrix row by row: ");
                       for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)

                    m[i][j] = input.nextInt();

            System.out.print("Sum of the matrix is " + sumMajorDiagonal(m));
        }

public static double sumMajorDiagonal(int[][] m) {
      
       int sum = 0;
       for (int i = 0; i < m.length; i++) {
           for (int j = 0; j < m[0].length; j++) {
               if (i == j) {
                   sum += m[i][j];
               }
           }
       }
      
       return sum;
   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote