-1

My program is designed to take a userinput for a square matrix - i want them to be able to enter each element as it would appear in the matrix. Instead, the program only takes one input and then loops infintely.

int main()
{
int dim;

printf("Input size of square matrix: ");
scanf("%d", &dim);

int mat[dim*dim];

printf("Input elements row by row: \n");

int p;
int q;
for (p = 0; p < dim; p++)
{
    for (q = 0; q < dim; q++)
    {
        scanf(" %d", mat[dim*p + q]);
    }
    printf("\n");
}

return 0;
}

1 Answers1

-1

Try this solution

    #include<stdio.h>
    int main()
    {
    int dim;
    
    printf("Input size of square matrix: ");
    scanf("%d", &dim);
    
    int mat[dim*dim];
    
    printf("Input elements row by row: \n");
    
    int p;
    int q;
    for (p = 0; p < dim; p++)
    {
        for (q = 0; q < dim; q++)
        {
            scanf("%d", &mat[dim*p + q]); // use & to store the value
        }
    }
    
   //Logic for to print array in matrix format
    for (p = 0; p < dim; p++)
    {
        for (q = 0; q < dim; q++)
        {
            printf("%d ", mat[dim*p + q]);
        }
        printf("\n");
    }
    
    return 0;
    }
Akshay Pawar
  • 784
  • 1
  • 7
  • 11
  • This is very helpful, thank you! As an additional question: how would I change the input loop so that, when the user is inputting their elements, it elements in the same 'row' appear on the same line when they are inputted? It seems to me that scanf adds a newline after the user hits enter. – Thomas Playsted Mar 22 '21 at 07:12