I am making a program to display matrices having 2 rows and 2 columns. The program works if I input 4 numbers, separated by space for both the matrices. Now if I input 5 numbers in each of the matrices, then I'm getting some weird output. For the first matrix the display is alright, but for the second matrix, whatever numbers I input for the first matrix, leaving the first four numbers, other numbers are getting inserted to second matrix.
#include <stdio.h>
int main(int argc, char *argv[])
{
int matr1[2][2], matr2[2][2], i = 0, j = 0;
printf("\nMATRIX-1: ");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
scanf("%d", &matr1[i][j]);
}
printf("MATRIX-2: ");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
scanf("%d", &matr2[i][j]);
}
printf("\nMATRIX-1");
for (i = 0; i < 2; i++) {
printf("\n");
for (j = 0; j < 2; j++)
printf("%d ", matr1[i][j]);
}
printf("\nMATRIX-2");
for (i = 0; i < 2; i++) {
printf("\n");
for (j = 0; j < 2; j++)
printf("%d ", matr2[i][j]);
}
printf("\n");
return 0;
}
OUTPUT:
MATRIX-1: 1 2 3 4 5
MATRIX-2: 1 2 3 4 5
MATRIX-1
1 2
3 4
MATRIX-2
5 1
2 3
Another thing I noticed is that if I press 'Enter' during the input, the cursor is going in the next line but the label 'MATRIX-1' remains where it is.
So is their any simple way to accept only certain number of items using scanf(), so that even if the user inputs more than that it won't going to insert that into next array, and display the label in the next line if the user inputs 'Enter'. (I know this can be done using do-while loops but I don't know how to use that within two for loops.)
P.S.- I am a beginner in C and may be these questions seem stupid but it would be very grateful for me if I get some help. Thanks in advance.