Summing the Major Diagonal of a Matrix in Java

Problem:

Write a method that sums all the integers in the major diagonal in an matrix of integers using the following header:

public static int sumMajorDiagonal(int[][] m)

Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements on the major diagonal.

Output:

Fill in this 4x4 matrix
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Diagonal sum is 34


Solution:

import java.util.Scanner;

public class twoDimentionalArrays
{
  public static int sumMajorDiagonal(int[][] m)
  {
    int sum =0;
    for(int i =0;i<m.length;i++)
      sum += m[i][i];
    return sum;
  }
  
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.println("Fill in this 4x4 matix");
    int[][] nums = new int[4][4];
    for (int i =0;i<nums.length;i++)
    {
      for (int j =0;j<nums[i].length;j++)
      {
        nums[i][j] = scan.nextInt();
      }
    }
    System.out.println("Diagonal sum is " + sumMajorDiagonal(nums));
  }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact