vess vess - 11 days ago 5
C Question

How to check if the elements in the main diagonal of a square matrix are the same?

I have to write a program which checks whether the elements (numbers) in the main diagonal of a square matrix (n x n) are the same (return 1 if they are, return 0 if they are not) using a function which is called by

main()
. The matrix is read from a file, done in
main()
.

Here is my function so far: (The function
checkdiag()
does not seem to be working, only the
main()
function is printing out data)

#include <stdio.h>
int checkdiag(int matrix[][100], int size)
{
int i,j;
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
if (matrix[i][100]==matrix[j][100])
{
return (1);
printf ("\nThe elements in the main diagonal of the matrix are the same.\n");
}
else
{
return (0);
printf ("\nThe elements in the main diagonal are not the same.\n");
}
}
}
}
int main (void)
{
int matrix[100][100];
int size, diag;
int i,j;
FILE *data;
data= fopen("data10.txt", "r");`

fscanf (data, "%d", &size);
printf ("The size of the matrix is %dx%d, and the matrix is:\n", size, size);
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
fscanf (data, "%d", &matrix[i][j]);
printf (" %d% ", matrix[i][j]);
}
printf ("\n");
}
diag= checkdiag(matrix, size);
}


If someone could please help me see where I am going wrong, I would appreciate it!

P.S The file I'm using is:

3
4 5 6
7 8 9
3 6 7


Where the first value in the file (3) is the size of the matrix. (i.e 3x3)

Answer
#include <stdio.h>

int main (void){

FILE *file = fopen("data.txt","r");
int size, i, j;

fscanf(file, "%d" , &size);
int matrix[size][size];

// Read the data into the matrix
for(i=0; i<size; i++){
    for(j=0; j<size; j++){
        fscanf(file, " %d", &matrix[i][j] );
    }
}

//determine if all diagonal entries in the matrix match the one at matrix[0][0]
i=matrix[0][0];
j=0;
while(j < size ){
    if(matrix[j][j] != i)
        break;
    else{
        j++;
    }
}

//if j is equal to the size of the matrix then voila! diagonal entries match.
if(j==size){
    printf("The diagonal is the same\n");
    return 1;
}else{
    printf("The diagonal is not the same\n");
    return 0;
}
}

This returns: The diagonal is not the same. For the input:

5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 2

This returns: The diagonal is the same. For the input:

5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 1