Define a class to accept values into an integer array of order 4 x 4 and check whether it is a DIAGONAL array or not An array is DIAGONAL if the sum of the left diagonal elements equals the
Advertisements
Question
Define a class to accept values into an integer array of order 4 x 4 and check whether it is a DIAGONAL array or not An array is DIAGONAL if the sum of the left diagonal elements equals the sum of the right diagonal elements. Print the appropriate message.
Example:
3 4 2 5 Sum of the left diagonal elements =
2 5 2 3 3 + 5 + 2 + 1 = 11
5 3 2 7 Sum of the right diagonal elements =
1 3 7 1 5 + 2 + 3 + 1 = 11
Answer in Brief
Advertisements
Solution
import java.util.*;
class DiagonalArray
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int mat[][]=new int[4][4];
int i,j;
//initializing the array
System.out.println("Enter the array elements");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
mat[i][j]=sc.nextInt();
}
//adding both the diagonal elements
int ld=0,rd=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i==j)
Id+=mat[i][j];
if(i+j==3)
rd+=mat[i][j];
}
}
//checking both the sums
if(ld=rd)
System.out.println("It is a DIAGONAL array");
else
System.out.println("It is not a DIAGONAL array");
}
}
Output:
Enter the array elements
3 4 2 5
2 5 2 3
5 3 2 7
1 3 7 1
It is a DIAGONAL array
shaalaa.com
Using Function Argument
Is there an error in this question or solution?
