3
Help me in the following exercise:
Make a program that defines an integer array of size 5x5. Next, initialize this matrix with random numbers between 5 and 9. Finally, your program must calculate the sum of the diagonal elements of this matrix. The program must print the generated matrix and the sum of its diagonal. Here is an example of output. Generated matrix:
5 6 7 8 9
9 5 6 7 8
8 9 5 6 7
7 8 9 5 6
6 7 8 9 5
The sum of the diagonal of the matrix is: 25.
The code I made, it doesn’t add up correctly:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char**argv){
int matriz[5][5];
int i, x, j, p;
int soma=0;
srand(time(NULL));
printf("Matriz gerada: ");
for(i=0; i<5; i++){
printf("\n");
for(j=0; j<5; j++){
x=5+(rand()%5);
printf("%3d", x);
matriz[i][j];
if(i==j){
for(p=0; p<5; p++){
soma+=matriz[i][j];
}
}
}
}
printf("\n");
printf("Soma da diagonal principal: %d", soma);
return 0;
}
The problem is that you don’t update the value of the matrix cell when you draw the number. Instead of doing
matriz[i][j];
, domatriz[i][j] = x;
on the third line within thefor
more internal. Probably is a typo. :)– Luiz Vieira
CORRECTION: I withdrew the for of the sum, I was adding several times. thank you Luiz Vieira!
– P Ribeiro
The third
for
with the variablep
doesn’t make sense. Like you said, the thirdfor
makes the sum count each cell in the middle five times.– Kyle A