Actually you need four somalin
and four somacol
, one for each row/column in valores
.
So once you popular the matrix, you will make a for
double to address each element and increment the sum of the respective row and column.
Step by step:
#include <stdio.h>
int
main(int argc, char ** argv) {
int valores[4][4];
int i, j, somacol[4], somalin[4];
First we get the values. Here you do it with printf()
and scanf()
, but it may suit you to isolate this functionality in a function so that later you want to get these values from a file or something like that.
for (i = 0; i < 4; i ++) {
for (j = 0; j < 4; j ++) {
When it’s time to call printf()
and friends, remember to put the format specifier (%d
in this case); otherwise none of the dynamic values you want to show.
printf("Informe os valores (%d, %d): ", i + 1, j + 1);
As to the scanf()
and so, remember to always start string format with a blank space for it to "eat" the return car you gave the previous time that called scanf()
. In addition, as the matrix is int
, must pass the address of the matrix element (with the operator &
):
scanf(" %d", &(valores[i][j]));
}
}
Then we start all the somalin
and somacol
to zero so we can use them with the increment operator +=
.
for (i = 0; i < 4; i ++) {
somalin[i] = somacol[i] = 0;
}
Now comes the part that matters: for
double so that in the body of the second for
, we have the indices of one of the sixteen elements of valores
. Just increment the sum of the row and column corresponding to that element:
for (i = 0; i < 4; i ++) {
for (j = 0; j < 4; j ++) {
somalin[i] += valores[i][j];
somacol[j] += valores[i][j];
}
}
After that, just do anything with the values and return. If you are doing this on main()
, remember that she returns int
and give a return 0;
before leaving. Good manners.
for (i = 0; i < 4; i ++) {
printf("Soma da %dª linha: %d\tSoma da %dª coluna: %d\n", i + 1, somalin[i], i + 1, somacol[i]);
}
return 0;
}