i am trying to calculate the sum of elements after the diagonal in 2D array but the problem is that the sum is always equal ZERO it do not change the answer.
where is the mistake in my code and how to fix it ?
i tried to use nested for loop and o tried to use one for loop but in both cases th eanswer still 0.
this is my code:
package test8;
import java.util.Scanner;
public class Question2 {
private int row = 4;
private int col = 4;
private int[][] matrix;
public Question2(int trow, int tcol) {
this.row = trow;
this.col = tcol;
}
public Question2(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
public int[][] fill() {
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for (int row = 0; row < data.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
}
System.out.println();
}
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.print(data[row][col] + " ");
}
System.out.println();
}
return data;
}
public int calculate(int[][] num) {
int sum = 0;
for (int row = 0; row < num.length; row++) {
//for (int col = row + 1; col < num[row].length; col++) {
// if(row == col){
System.out.println(row);
sum += num[row][row];
// }
//}
}
System.out.println("the sum is: " + sum);
return sum;
}
public static void main(String[] args) {
Question2 q2 = new Question2(3, 3);
int[][] ma = q2.fill();
q2.calculate(ma);
}
}
this is the output:
1 2 3
4 5 6
7 8 9
0
1
2
the sum is: 15