Sum of Diagonals of a Matrix
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 in JAVA.
Example :-
Program is below :-
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");
}
}
}
Comments
Post a Comment