MikiBV
MikiBV

Reputation: 43

Why I do not get proper result with matrix elements?

I want to write code which will add only diagonal elements.

    import java.util.Scanner;

public class SabMat {
  public static void main(String[] args) {

          Scanner input = new Scanner(System.in);
         double [][] matrix = new double [4][4];

      System.out.print("Enter matrix elements by row");
        for (int i=0; i < matrix.length; i++) {
           matrix[i][0] = input.nextDouble();
           matrix[i][1] = input.nextDouble();
           matrix[i][2] = input.nextDouble();
           matrix[i][3] = input.nextDouble();
        }

   int total=0;
   for (int row=0; row < matrix.length; row++) {
    for (int column=0; column < matrix[row].length; column++) {
          if (row == column){
           total += total + matrix[row][column];
         } else if (row!=column){
           total = 0;
         }
       }
    }

      System.out.println("The sum of elements in the major diagonal is"+total);
  }
}

The result is not good! The problem is only (3,3) element is added to total not the previous three. How to solve this?

Upvotes: 1

Views: 40

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Your code does not work because it resets the total every time you're off the main diagonal.

Note that you do not need two loops if all you want is to total the elements of the diagonal: rather than running two nested loops and waiting for row == column, run a single loop, and total up the values of matrix[i][i].

for (int i = 0 ; i != matrix.length ; i++) {
    total += matrix[i][i];
}

Upvotes: 2

Related Questions