0
I need to do a program that takes out the diagonals of a matrix. As an example
But I’m having a hard time. Follows code:
#include <stdio.h>
#include <math.h>
#define M 4
#define N 3
int main(){
int i, j, soma=0;
int mat[M][N]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}}, result[M+N-1];
for(i=0; i<M+N-1; i++){ //deixar todos valores do vetor iguais a zero
result=0;
}
int a, b, k=0, aux; //auxiliares
for(i=M-1; i>=0; i--){
for(j=N-1; j>=0; j--){
result[k]=mat[j]; //posição 0 do vetor recebe posição 4x3 da matriz;
a=i;
b=j;
while(a>=0 && b<N && b>=0){ //verificar se linha>=0, coluna<N e >=0
a--; //decrementa linha
b++; //acrescenta coluna
result[k]+=mat[a]; //valor da posição 0 do vetor soma com o proximo valo da diagonal superior direita
}
k++; //avança para proxima posição do vetor*/
}
}
for(i=0; i<M; i++){
for(j=0; j<N; j++){
printf("\t%d ", mat[j]);
}
printf("\n");
}
printf("\n");
for(i=0; i<M+N-1; i++){
printf("%d ", result);
}
}
At first I’m just trying to sum up the diagonals and then use the threads to carry out the processes. Can someone help me? Thank you in advance.
The logic is quite simple: considering the elements in the line
i
and columnj
, just add up all that sum ofi+j
be itz
, beingz
the result matrix line. In other words:r[0]
shall be the sum of all items thei+j
is 0, that is,mat[0][0]
;r[1]
shall be the sum of all items thei+j
is 1, that is,mat[0][1]+mat[1][0]
; thus successively.– Woss