Home > Enterprise >  Unexpected output while printing 2 array (matrix)
Unexpected output while printing 2 array (matrix)

Time:12-05

output is printing only few elements of matrix that to in a wrong order i think something is wrong with the printing loop but unable to figure it out

#include <stdio.h>

int main()
{
    int x=0, y=0;
    int a[x][y];
    printf("enter the number of rows in first matrix:\n");
    scanf("%d", &x);
    printf("enter the number of columns in first matrix:\n");
    scanf("%d", &y);
    printf("enter elements of first matrix\n");
    for (int i = 0; i < x; i  )
    {
        for (int j = 0; j < y; j  )
        {
            printf("enter element %d %d\n", i, j);
            scanf("%d", &a[i][j]);
        }
    }
    for (int p = 0; p < x; p  )
    {
        for (int q = 0; q < y; q  )
        {
            printf("%d\t", a[p][q]);
        }
        printf("\n");
    }

    return 0;
}

CodePudding user response:

You're initializing your 2d array with 0 rows and 0 columns.
You need to move int a[x][y] down under scanf("%d", &y);

#include <stdio.h>

int main() {
    int x, y;
    printf("enter the number of rows in first matrix:\n");
    scanf("%d", &x);
    printf("enter the number of columns in first matrix:\n");
    scanf("%d", &y);
    int a[x][y];
    printf("enter elements of first matrix\n");
    for (int i = 0; i < x; i  ) {
        for (int j = 0; j < y; j  ) {
            printf("enter element %d %d\n", i, j);
            scanf("%d", &a[i][j]);
        }
    }
    for (int p = 0; p < x; p  ) {
        for (int q = 0; q < y; q  ) {
            printf("%d\t", a[p][q]);
        }
        printf("\n");
    }

    return 0;
}

CodePudding user response:

You're declaring the matrix before receiving the size of the matrix (you're variables x and y). In your code, the matrix is declared as a[0][0].

Solution:

#include <stdio.h>

int main() {
    int x, y;
    printf("enter the number of rows in first matrix:\n");
    scanf("%d", &x);
    printf("enter the number of columns in first matrix:\n");
    scanf("%d", &y);
    int a[x][y];
    printf("enter elements of first matrix\n");
    for (int i = 0; i < x; i  ) {
        for (int j = 0; j < y; j  ) {
            printf("enter element %d %d\n", i, j);
            scanf("%d", &a[i][j]);
        }
    }
    for (int p = 0; p < x; p  ) {
        for (int q = 0; q < y; q  ) {
            printf("%d\t", a[p][q]);
        }
        printf("\n");
    }

    return 0;
}
  • Related