add rows of 2D arrays in processing

user10178710 :

I'm trying to create a function to sum up the rows of 2D arrays. I already have the code, but the return value does not seem to be working. Just need your thoughts as I need this finished in 24 hours :D

int sumRows(int ArrayR[][]){
int row=3;
  int col=3;
  int sumR = ArrayR[0][0];
  //int [] sumR = new int[row];
  for (int i = 0; i<row; i++){
    for (int j = 0; j<col; j++){
    sumR+=ArrayR[i][i];
    }
   }
  return sumR;
}

Thanks!

Rabbid76 :

If you want to sum the elements of a matrix, then there are 2 issues in your code:

You have to initialize sumR by 0, else the element at index [0][0] would be added twice:

int sumR = 0;

Further you have 2 control variables i and j in the nested loop, but you use i for the column and the rows when you look up the matrix ArrayR.

Change

sumR+=ArrayR[i][i];

to

sumR+=ArrayR[i][j];

focus on [i][j]


But if you want to sum each row of a matrix, then you have to return an array of sums from the function and you have to store the sum of each row separately in an element of the array. You can do it like this:

int[] sumRows(int ArrayR[][]){

    int row = ArrayR.length;
    int[] sumR = new int[row];
    for (int i = 0; i < row; i++){

        int col = ArrayR[i].length; 
        sumR[i] = 0;  
        for (int j = 0; j < col; j++){
            sumR[i] += ArrayR[i][j];
        }
    }
    return sumR;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71349&siteId=1