0

I have a function that calculates the average value of each columns, but when I run it, it gives me : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

// function to calculate the average value of columns of the given matrix
static void povprecje_stolpci(double matrix[][]) {
    int i, j;
    double zbir = 0, prosek = 0; // prosek - variable for average
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            zbir = (int) (zbir + matrix[j][i]); // zbir variable to calculate the sum of the elements in each columns
        }
        prosek = (int) (zbir / matrix[i].length); // average of the columns
        System.out.print(prosek); // printing the average
        zbir = 0; // setting the sum to 0 for the next element 
        System.out.print(" ");
    }

}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

0

the problem is with zbir = (int) (zbir + matrix[j][i]); section of your code which you need to change it:

because in first loop you iterate through the rows of array and in inner loop iterate throgh the columns

zbir = (int) (zbir + matrix[i][j]);

complete code:

static void povprecje_stolpci(double matrix[][]) {
    int i, j;
    double zbir = 0, prosek = 0; // prosek - variable for average
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            zbir = (int) (zbir + matrix[i][j]); // zbir variable to calculate the sum of the elements in each
                                                // columns
        }
        prosek = (int) (zbir / matrix[i].length); // average of the columns
        System.out.print(prosek); // printing the average
        zbir = 0; // setting the sum to 0 for the next element
        System.out.print(" ");
    }
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36