Lelre Ferreira
Lelre Ferreira

Reputation: 11

How can I sum the rows of Matrix ignoring the first line? In C

I did the following:

for (int i = 0; i < tamLinhas; i++) {
    for (int j = 0; j < tamColunas; j++) {
        if (i >= 0) {
            vetormedia[j] = (informacoes[i][j] + informacoes[i][j]) / tamVetor;
        }
    }
}

I'm trying to record in an array the result of the sum of the matrix's rows but I need to ignore the first line of the Matrix.

In a nutshell, the values of the first line cannot be included in the sum. I just cannot get it done right. I've been trying for hours...

Upvotes: 0

Views: 45

Answers (1)

bruno
bruno

Reputation: 32586

To bypass the first line of the matrix informacoes just start the iteration at the index 1 rather than 0:

for (int i = 1; i < tamLinhas; i++) {

Note your test if (i >= 0) is useless even in your initial case because i cannot be negative

That line is very strange :

vetormedia[j] = (informacoes[i][j] + informacoes[i][j]) / tamVetor;

because you do not sum the rows and you save that value in the same place for all the lines.

To just sum the rows of each line separately and save the result in vetormedia :

for (int i = 1; i < tamLinhas; i++) {
  int sum = 0
  for (int j = 0; j < tamColunas; j++) {
    sum += informacoes[i][j];
  }
  vetormedia[i] = sum;
}

Supposing tamLinhas values 3 and tamColunas values 4 and informacoes is the following matrix :

1 2 3 4
4 5 6 7
8 9 0 1

after the previous loop vetormedia will be :

x 22 18

where "x" design any value because the first line of the matrix is bypassed

Do you want that ?

Upvotes: 1

Related Questions