Sum of both diagonal elements of a matrix in java
In this tutorial, we will write a java program to find sum of diagonal elements of matrix.
First, we will write the algorithm to print sum of diagonal elements of matrix, then we will write the compiled java code of this program.
Our task is pretty simple. We have to ask the user to input a matrix, then we will traverse the diagonal elements and calculate their sum.
A square matrix of size r*c will be passed as input by the user, then the program will print the input matrix and the sum of both diagonal elements of matrix.
We will access the boundary elements using the below approach.
Sum of Diagonal Elements of Matrix in Java Algorithm:
Step 1: Enter the number of Rows (r).
Step 2: Enter number of Columns (c).
Step 3: Read the elements of Matrix (arr[i][j]).
Step 4: Read both diagonal elements using for loop (i and j).
Step 5: Store sum of diagonal elements in (SumofDiagonal).
Step 6: Print sum of diagonal elements.
Sum of Diagonal Elements of Matrix in Java
import java.util.*;
class Sum_of_Both_Diagonals
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int SumofDiagonal=0;
System.out.println("Enter the number of Rows:");
int r=sc.nextInt();
System.out.println("Enter the number of Columns:");
int c=sc.nextInt();
int arr[][]=new int[r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print("Enter the Element of Matrix:");
arr[i][j]=sc.nextInt();
}
}
System.out.println("Input Matrix:");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println(" ");
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(i==j)
{
SumofDiagonal=SumofDiagonal+arr[i][j];
}
else if(i+j==r-1 && j!=i)
{
SumofDiagonal=SumofDiagonal+arr[i][j];
}
}
}
System.out.println("Sum of Both Diagonal Elements:"+Sumof Diagonal);
}
}
-----------
Output:-
-----------
Enter the number of Rows:
3
Enter the number of Columns:
3
Enter the Element of Matrix:1
Enter the Element of Matrix:5
Enter the Element of Matrix:9
Enter the Element of Matrix:8
Enter the Element of Matrix:7
Enter the Element of Matrix:5
Enter the Element of Matrix:3
Enter the Element of Matrix:2
Enter the Element of Matrix:4
-----------------------------
Input Matrix:
1 5 9
8 7 5
3 2 4
--------------
Sum of Both Diagonal Elements:24
Checkout:- Sort Matrix in Ascending Order Java
0 Comments
Just write down your question to get the answer...