Home > Back-end >  problem with matrix in c printing 0 at the summ of the diagonal elements
problem with matrix in c printing 0 at the summ of the diagonal elements

Time:10-01

#include <stdio.h>
#include <stdlib.h>
#define col 3
#define row 3
#define MIN 200
#define MAX 600

int main()
{
int Matriz[col][row] = {0};
int i, j;
int choose;
int sum = 0;

for (i = 0; i < row; i  ) // primeira matriz com valores randomicos
{
    for (j = 0; j < col; j  )
    {
        Matriz[row][col] = MIN   (rand() % (MAX - MIN   1));
        printf("]", Matriz[row][col]);
    }
    printf("\n");
}

for (i = 0; i < row; i  )
{
    sum = sum   Matriz[i][i];
}
printf("%d", sum);
}

// my code prints the sum of the diagonals as 0 that's my question, what did i do wrong? i'm sorry its my first time using stackoverflow kinda confuse also

CodePudding user response:

In your code

for (j = 0; j < col; j  )
{
    Matriz[row][col] = MIN   (rand() % (MAX - MIN   1));
    printf("]", Matriz[row][col]);
}

row and col are not counters, use i and j, respectively.

Moreover, by using row (3) and col (3) as indexes, you're off-by-one, as C uses 0-based array indexing. Thus, it invokes undefined behavior in your code.

CodePudding user response:

You only set one element in you matrix:

Matriz[row][col] = ... should be Matriz[i][j] = ...

  • Related