0

This is a program for adding matrices but it seems that the compiler skips the second scanf in the second nested for loop.

void input_add_matrices() {
    printf("Input number of rows for matrices: "); scanf("%d", &nrow_matrix1); getchar();
    printf("Input number of columns for matrices: "); scanf("%d", &ncolumn_matrix1); getchar();
    printf("\nInput elements for matrix 1:\n");
    for(i=0; i<nrow_matrix1; i++){
        for(j=0; j<ncolumn_matrix1; j++){
            scanf("%d", &element_matrix1[i][j]); getchar();
        }
    }
    nrow_matrix2=nrow_matrix1;
    ncolumn_matrix2=ncolumn_matrix2;
    printf("\nInput elements for matrix 2:\n");
    for(i=0; i<nrow_matrix2; i++){
        for(j=0; j<ncolumn_matrix2; j++){
            scanf("%d", &element_matrix2[i][j]); getchar();
        }
    }
}

Is this a compiler error or something else? Please help.

Output is:

Input number of rows for matrices: 2
Input number of columns for matrices: 2

Input elements for matrix 1:
1
2
1
2

Input elements for matrix 2:

Matrix 2 is blank.

  • The `getchar` call is not needed. The `"%d"` format for `scanf` skips leading whitespace, which includes newline (which I'm guessing you're worried about). – Some programmer dude Dec 16 '16 at 12:35
  • 1
    Even if I omit the 'getchar' function it still occurs. – Alzer Casiño Dec 16 '16 at 12:37
  • Put a breakpoint on that second loop and debug your code. If it stops there, then it's not the compiler who is skipping this loop. Perhaps your program does do what you expect it to do, but it doesn't mean that the compiler is skipping anything. – barak manos Dec 16 '16 at 12:38

1 Answers1

5

I think it's the code line ncolumn_matrix2=ncolumn_matrix2; which leads to ncolumn_matrix2 to be 0, such that the loop is not entered

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58