Reputation:
I'm creating a part of a program which should allow the user to input the dimensions of a square matrix, input a value for each element, and then print out the resulting matrix. Pretty sure the issue lies within one of the for loops, as only the last line of the matrix is being printed; for example if I wanted a 3x3 matrix of [1 2 3][4 5 6][7 8 9], the program would print [7 8 9][7 8 9][7 8 9] instead.
//initialise variables
int n_i = 0;
int input_matrix[n_i][n_i];
int row;
int column;
//dimensions of matrix
printf("Enter a value for the dimensions of a square matrix: \n");
printf(">>");
scanf("%i", &n_i);
//elements of matrix
for(row = 0; row < n_i; ++row)
{
for(column = 0; column < n_i; ++column)
{
printf("Enter a value for the [%i][%i] element: \n", row, column);
printf(">>");
scanf("%d", &input_matrix[row][column]);
}
}
//display matrix
printf("%ix%i matrix: \n", n_i, n_i);
for(row = 0; row < n_i; ++row)
{
for(column = 0; column < n_i; ++column)
{
printf("%d ", input_matrix[row][column]);
printf("%i ", n_i);
if(column == n_i)
{
printf("\n");
}
}
}
Upvotes: 0
Views: 32
Reputation: 222724
This code:
int n_i = 0;
int input_matrix[n_i][n_i];
attempts to create an empty matrix. Define the matrix only after n_i
is set to the desired value.
The condition in this if
statement:
if(column == n_i)
{
printf("\n");
}
will never be true since it is inside a loop which executes only while column < n_i
. The last iteration of the loop occurs when column == n_i-1
.
Upvotes: 1