Hi Readers,
In this programme we have square matrix of size N x N. We need to find the difference between sum of forward diagonal and backward diagonal.
so N = 3
And matrix numbers are
11 2 4
4 5 6
10 8 -12
So sum of forward diagonal will be = 11 + 5 + (-12) that is 4
So sum of backward diagonal will be = 4 + 5 + 10 that is 19
So difference will be 19 - 4 = 15. This difference will be positive.
First we will input N number. Then we will input all the numbers to form square matrix. We will make matrix from Java 2D Array.
In this programme we have square matrix of size N x N. We need to find the difference between sum of forward diagonal and backward diagonal.
For example :-
we have a matrix of 3 x 3so N = 3
And matrix numbers are
11 2 4
4 5 6
10 8 -12
So sum of forward diagonal will be = 11 + 5 + (-12) that is 4
So sum of backward diagonal will be = 4 + 5 + 10 that is 19
So difference will be 19 - 4 = 15. This difference will be positive.
Java Programme to find difference of diagonals :-
First we will input N number. Then we will input all the numbers to form square matrix. We will make matrix from Java 2D Array.
package com.techiekunal.easy; import java.util.Scanner; public class MatrixDiagonalDifference { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int[][] arr; int sumFwdDiagonal = 0; int sumBwdDiagonal = 0; n = in.nextInt(); arr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = in.nextInt(); } } for (int i = 0, j = 0; i < n; i++, j++) { sumFwdDiagonal = sumFwdDiagonal + arr[i][j]; } for (int i = 0, j = n-1; i < n; i++, j--) { sumBwdDiagonal = sumBwdDiagonal + arr[i][j]; } System.out.println(Math.abs(sumFwdDiagonal- sumBwdDiagonal)); in.close(); } }You will give your inputs from Console while running this programme.
0 Comments
Post a Comment