You actually need four somalin
and four somacol
, one for each row / column in valores
.
So, after you've populated the array, you're going to make a% double% to address each element and increment the sum of the row and column.
Walkthrough:
#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 this with for
and printf()
, but you may want to isolate this functionality in a function so in case you want to get these values from a file or something.
for (i = 0; i < 4; i ++) {
for (j = 0; j < 4; j ++) {
When calling scanf()
and friends, remember to put the format specifier ( printf()
in this case); otherwise none of the dynamic values you want to display will appear.
printf("Informe os valores (%d, %d): ", i + 1, j + 1);
As for %d
and the like, remember to always get the string format with a blank space so that it "eats" the carriage return you gave in the previous time called scanf()
. Also, since the array is of scanf()
, you have to pass the address of the array element (with the int
operator):
scanf(" %d", &(valores[i][j]));
}
}
Then, we start all &
and somalin
to zero so that we can use them with the somacol
operator.
for (i = 0; i < 4; i ++) {
somalin[i] = somacol[i] = 0;
}
Now comes the part that interests: We make a% double_de% so that, in the body of the second +=
, we have the indexes of one of the sixteen elements of for
. Simply 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're doing this on for
, remember that it returns valores
and give main()
before exiting. These are 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;
}