Matrix with the diagonal set to 0, and the rest of the elements set from 1 to n (in C)

Advertisements

Firstly, a number N has to be input, and the matrix is of NxN dimensions then. The diagonal of the matrix has to be all 0, the elements of the matrix above the diagonal have to be from 1 to N diagonally, and the elements under the diagonal need to be filled from -1 to -N also diagonally. It should be something like this (if N=5):

But the problem that I have is that I print it out like this:

and I don’t know how to fix it.

This is the code that I have:

`#include <stdio.h>

int main() {
    int matrix[50][50], i, j, N;
    
    printf("N: ");
    scanf("%d",&N);

    int k=0;
    for(i=0; i<N; i++){
        for(j=0; j<N; j++){
            if(i==j){
                matrix[i][j]=0;
            }
            else if(j>i && i!=j){
                for(k=0; k<N; k++){
                    matrix[k-1][j]=k;
                }
            }
            else if(j<i && i!=j){
                for(k=0; k<N; k++){
                    matrix[i][k-1]=-k;
                }
            }
        }
    }

    printf("Matrix:\n");
    for (i=0; i<N; i++) {
        for (j=0; j<N; j++)
            printf("%4d", matrix[i][j]);
        printf("\n");
    }
    return 0;
}`

I would really appreciate the help.

>Solution :

Here is you code modified, notice that 3 inner loops are removed with only one line.

second, you ask for the number N, however due to statically initialisation to maximum 50, you should as well verify that it is not. otherwise segmentation fault will happen.

or if you want to allow N >50 then better to do dynamic allocation on matrix.

#include <stdio.h>

int main() {
    int matrix[50][50], i, j, N;
    printf("N: ");
    scanf("%d", &N);
    if (N > 50){
        printf("N should be smaller than 50, \n");
        N = 50;
    }

    for(i=0; i<N; i++){
        for(j=0; j<N; j++){
                matrix[i][j]= j - i;
        }
    }

    printf("Matrix:\n");
    for (i=0; i<N; i++) {
        for (j=0; j<N; j++)
            printf("%4d", matrix[i][j]);
        printf("\n");
    }
    return 0;
}

Leave a ReplyCancel reply