Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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):

enter image description here

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here 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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading