Find sum of elements below diagonal in matrix - program in java


Write a program to Find sum of elements below diagonal in matrix in java

Sum of elements below diagonal = 5+8+7+4+3+2= 29

Logic behind finding sum of elements below diagonal is:
          //Logic to calculate sum of elements below diagonal.
          int sum=0;
          for (int i = 1; i < rows; i++) {
                 for (int j=i-1 ; j>=0 ; j--) {
                       sum= sum + matrix[i][j];
                 }
                
          }

Example/ Full Program/SourceCode to Find sum of elements below diagonal in matrix in java >
package matrix;
import java.util.Scanner;
/** Copyright (c), AnkitMittal  JavaMadeSoEasy.com
Find sum of elements below diagonal in matrix in java
*/
public class SumOfElementsBelowDiagonal {
   public static void main(String...args) {
         
          Scanner scanner = new Scanner(System.in);
          System.out.print("Enter number of rows/columns in matrix : ");    //rows and columns in matrix must be same.
          int rows = scanner.nextInt();
          int columns=rows;
          int[][] matrix = new int[rows][rows];
         
          System.out.println("Enter the elements in matrix :");
          for (int i = 0; i < rows; i++) {
                 for (int j = 0; j < columns; j++) {
                       matrix[i][j] = scanner.nextInt();
                 }
          }
         
          //Logic to calculate sum of elements below diagonal.
          int sum=0;
          for (int i = 1; i < rows; i++) {
                 for (int j=i-1 ; j>=0 ; j--) {
                       sum= sum + matrix[i][j];
                 }
                
          }
          System.out.println("\nMatrix is : ");
          for (int i = 0; i < rows; i++) {
                 for (int j = 0; j < columns; j++) {
                       System.out.print(matrix[i][j] + " ");
                 }
                 System.out.println();
          }
          System.out.println("sum of elements below diagonal is: "+sum);
   }
}
/*OUTPUT
Enter number of rows/columns in matrix : 4
Enter the elements in matrix :
1
2
3
4
5
6
7
8
8
7
6
5
4
3
2
1
Matrix is :
1 2 3 4
5 6 7 8
8 7 6 5
4 3 2 1
sum of elements below diagonal is: 29
*/


We wrote a program to Find sum of elements below diagonal in matrix in java.

Previous program                                                                  Next program


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>


>Pattern/Pyramid generating programs





No comments:

Post a Comment