First Way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
class MatDiagSum{ public static void main(String args[]){ int size = 6; int mat[][] = new int[size][size]; // input ints in matrix for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ mat[i][j] = i+j; } } // first print our matrix for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ System.out.print(mat[i][j] + " "); } System.out.println(); } // declare few required variables int sum=0; int nexti=0; int nextj=0; // lets do sum of first half of diagonals and print them for(int i=0;i<size;i++){ for(int j=0;j<=i;j++){ sum+=mat[nexti][nextj]; nexti--; nextj++; if(nexti<0) { break; } } System.out.println("Sum of " + i + " diag is " + sum); nexti=i+1; nextj=0; sum=0; } // lets do remaining half-1 nexti = size-1; nextj = 1; for(int i=0; i<(size-1);i++){ for(int j=0;j<((size-i)-1);j++){ sum+=mat[nexti][nextj]; nexti--; nextj++; if(nextj>(size-1)){ break; } } System.out.println("Sum of " + (size+i) + " diag is " + sum); nexti = size-1; nextj = i+2; sum=0; } } } |
Second Way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
class MatDiagSumOtherSide{ public static void main(String args[]){ int size = 6; int mat[][] = new int[size][size]; // input ints in matrix for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ mat[i][j] = i+j; } } // first print our matrix for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ System.out.print(mat[i][j] + " "); } System.out.println(); } // declare few required variables int sum=0; int nexti=0; int nextj=size-1; // lets do sum of first half of diagonals and print them for(int i=(size-1);i>-1;i--){ for(int j=0;j<=(size-i);j++){ sum+=mat[nexti][nextj]; nexti++; nextj++; if(nextj>(size-1)) { break; } } System.out.println("Sum of " + (size-i) + " diag is " + sum); nexti=0; nextj=i-1; sum=0; } // lets do remaining half-1 nexti = 1; nextj = 0; for(int i=0; i<(size-1);i++){ for(int j=0;j<((size-i)-1);j++){ sum+=mat[nexti][nextj]; nexti++; nextj++; if(nexti>(size-1)){ break; } } System.out.println("Sum of " + (size+i) + " diag is " + sum); nexti = i+2; nextj = 0; sum=0; } } } |