top of page
Writer's pictureSatyam Gupta

Sum of Diagonals of a Matrix in JAVA

Sum of Diagonals of a Matrix

Easiest Program to calculate the sum of LEFT and RIGHT  diagonal of a Matrix of order (m x n) where m = n


Example :-


Logic

 

Program :-


import java.io.*;

import java.util.*;

class Matrix1

{

    public static void main(String args[])

    {

        int n,i,j; // variable for intializing array and loop

        int left=0,right=0; // variables to store sum of left and right diagonal of the Matrix

        Scanner in= new Scanner(System.in);

        System.out.println("Enter Array Capacity");

        n= in.nextInt(); // To Input Array Capacity

        int ar[][]=new int[n][n]; // Array Defined

        int k= n-1; // This variable will help to store sum of right diagonal

        System.out.println("Enter Array Elements");

        for(i=0;i<n;i++)

        {

            for(j=0;j<n;j++)

            {

                ar[i][j]= in.nextInt(); // Input Array Elements

            }

        }

        for(i=0;i<n;i++)

        {

            left = left + ar[i][i];

            right = right + ar[i][k-i];

        }

        System.out.println("Sum of Left Diagonal = "+left); // Display sum of Left Diagonal

        System.out.println("Sum of Right Diagonal = "+right); // Display sum of Right Diagonal

        System.out.println("Original Matrix"); // Display Original Matrix

        for(i=0;i<n;i++)

        {

            for(j=0;j<n;j++)

            {

                System.out.print(ar[i][j]+"\t");

            }

            System.out.println("\t");

        }

    } // end of main method

} // end of class


 

Note : The program is written in the easiest way possible so try understand it. If you face any problem in understanding this program than feel free to contact/comment.


All the Best :)

Keep Learning :)

124 views0 comments

Recent Posts

See All

Comentários


Post: Blog2_Post
bottom of page