How to add the diagonal of an array in C?

3

Help me in the following exercise:

Make a program that defines an array of 5x5 size integers. Then, initialize this array with random numbers between 5 and 9. Finally, your program must calculate the sum of the diagonal elements of that matrix. The program should print the generated matrix and the sum of its diagonal. Here is an example output. Matrix generated:

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 did, does not sum 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;
}
    
asked by anonymous 05.05.2016 / 01:05

1 answer

4

Your code had basically two problems. As @Luiz Vieira mentioned , you were not saving the value of x in the array. Also, as you yourself noticed, there was an unnecessary loop making the sum.

In order to make it easier to read, all the redundant variables were removed and a slight wipe in the code was solved, solving the two problems mentioned above:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char**argv){
    int matriz[5][5];
    int i, j;
    int soma=0;

    srand( time( NULL ) );

    printf( "Matriz:\n" );
    for( i = 0; i < 5; i++ ){
        for( j = 0; j < 5; j++ ){
            matriz[i][j] = 5 + rand() % 5;
            printf( "%3d", matriz[i][j] );
            if( i==j ){
                soma += matriz[i][j];
            }
        }
        printf( "\n" );
    }
    printf( "Soma da diagonal principal: %d", soma );
    return 0;
}

See working at IDEONE .

Now, imagining that you have to add the diagonal of a preexisting array, see how the sum loop would look if it were independent of the rest:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char**argv) {
    int matriz[5][5];
    int i, j;
    int soma = 0;

    srand( time( NULL ) );

    /* gerando a matriz */
    printf( "Matriz:\n" );
    for( i = 0; i < 5; i++ ) {
        for( j = 0; j < 5; j++ ) {
            matriz[i][j] = 5 + rand() % 5;
            printf( "%3d", matriz[i][j] );
        }
        printf( "\n" );
    }

    /* fazendo a soma */
    for( i = 0; i < 5; i++ ) {
        soma += matriz[i][i];
    }
    printf("Soma da diagonal principal: %d", soma);

    return 0;
}

See working at IDEONE .

    
13.04.2017 / 14:59