×
FREE ASSISTANCE FOR THE INQUISITIVE PEOPLE
Tutorial Topics
X
softetechnologies
Advance Array Examples In Java Sum of the Border elements of 2D Array
Sum of the diagonal elements of 2D Array - Java
12910    Arnab De    04/12/2018

create a double dimension array of size 4 x 4 and calculate the sum of the diagonal elements.

In a square matrix diagonal elements are two type. In case of left diagonal the row number and column number are same. that is row no = col no. And in case of right diagonal row number + column number = (Total row number - 1). Therefore, we just travel the array once and add all the elements which meet the above conditions.

softetechnologies
import java.util.*;
public class Diagonal2D
{
    public static void main(String []args)
    {
        Scanner sc=new Scanner(System.in);
        int s=0;
        int [][]arr=new int[4][4];
        for(int r=0;r<4;r++)
        {
            for(int c=0;c<4;c++)
            {
                arr[r][c]=sc.nextInt();
            }
        }
        for(int r=0;r<4;r++)
        {
            for(int c=0;c<4;c++)
            {
                if((r==c) || (r+c==3))    
                {
                    s+=arr[r][c];
                }
            }
        }
        System.out.println("Sum Is : " + s);
    }
}
softetechnologies
Advance Array Examples In Java Sum of the Border elements of 2D Array
softetechnologies
Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
Enter New Comment
Comment History
No Comment Found Yet.
Sri Sri Ramakrishna Paramahamsa
All religions are true. God can be reached by different religions. Many rivers flow by many ways but they fall into the sea. They all are one.
Sri Sri Ramakrishna Paramahamsa
5270
73.45
Today So Far
Total View (Lakh)
softetechnologies
26/05/2018     51989
25/06/2018     43805
01/01/2018     42870
28/06/2017     40611
02/08/2017     39420
01/08/2017     33623
06/07/2017     33421
15/05/2017     32731
14/07/2017     28988
11/09/2018     28846
softetechnologies