Thread: Sum of the diagonal numbers of a matrix

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    5

    Sum of the diagonal numbers of a matrix

    Hi, ive been having some problem here, can't figure out whats wrong...
    when i type in 2 2 the matrix should be a 2x2 one, so then i type in the numbers 1 2 3 4, so the matrix first line is 1 2 and second line is 3 4, the sum of the diagonal numbers should be 1+4 = 5, but i keep getting 10 as answer, whats wrong?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
        
        int L, C, soma = 0;
        
        scanf("%d", &L);
        scanf("%d", &C);
        
        int matriz[L][C];
        
        for(int i=0; i<L; i++){
            for(int j=0; j<C; j++){
                scanf("%d", &matriz[i][j]);
            }
        }
        
        for(int i=0; i<L; i++){
            for(int j=0; j<C; j++){
                soma += matriz[i][i];
            }
        }
        printf("%d\n", soma);
        system("pause");
        return 0;
    }

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    You're adding the diagonal numbers twice, because you are running the "i" loop twice. Try just
    Code:
    for(int i=0; i<C;i++){
                soma += matriz[i][i];
    }
    and leave out the "j" loop.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    5
    figured out what it was! some+=matriz[i][i] should come in the first loop not in the second

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    5
    Quote Originally Posted by TheBigH View Post
    You're adding the diagonal numbers twice, because you are running the "i" loop twice. Try just
    Code:
    for(int i=0; i<C;i++){
                soma += matriz[i][i];
    }
    and leave out the "j" loop.
    yea i just noticed thanks anyway

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A square matrix with complex numbers
    By bchudomelka in forum C Programming
    Replies: 5
    Last Post: 05-28-2010, 06:35 PM
  2. Putting numbers in a Matrix.
    By mfm12002 in forum C Programming
    Replies: 14
    Last Post: 03-19-2010, 02:35 PM
  3. Diagonal
    By shardin in forum C Programming
    Replies: 6
    Last Post: 09-07-2007, 06:27 AM
  4. tic-tac-toe diagonal
    By abrege in forum C++ Programming
    Replies: 5
    Last Post: 01-03-2003, 01:10 PM
  5. Diagonal Matrix
    By mlupo in forum C Programming
    Replies: 1
    Last Post: 12-04-2002, 10:02 PM