Diagonal Sum


Get the sum of the diagonal values and add them. Just had some time trying to play around arrays.

1st. Get the all diagonal values. Add the numbers for each line segment.
2nd. Add the the total of the two line segments.

I had to traverse the table matrix to get the numbers within the line segments. It’s basic array.

package com.areyes1.algo;

public class DiagonalSum {
	static int[][] arrNumber = new int[][] {
			{1,2,3,4,6},
			{1,2,3,7,5},
			{1,2,3,4,5},
			{1,5,3,4,5},
			{8,2,3,4,9}
			};
	static int diagnoalSum() {
		int startingCounter = 0;
		int sum1st = 0;
		int sum2nd = 0;
		for(int i=0;i<arrNumber.length;i++) {
			for(int j=0;j<arrNumber[i].length;j++) {
				if(j == startingCounter) {
					sum1st += arrNumber[i][startingCounter];
				}
			}
			startingCounter++;
		}
		
		System.out.println(sum1st);
		startingCounter = arrNumber.length - 1;
		for(int i=0;i<arrNumber.length;i++) {
			for(int j=arrNumber[i].length - 1;j>=0;j--) {
				if(j == startingCounter) {
					sum2nd += arrNumber[i][startingCounter];
				}
			}
			startingCounter--;
		}
		System.out.println(sum2nd);
		return sum1st + sum2nd;
	}
	public static void main(String[] args) {
		diagnoalSum();
	}
}

The code can be modified as long as the table matrix is proportional, that is number of rows = number of columns.

Output:
1 + 2 + 3 + 4 + 9 = 19
6 + 7 + 3 + 5 + 8 = 29
19 + 29 = 48

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s