Home > Software design >  Matrix input ends with -1 and -2
Matrix input ends with -1 and -2

Time:01-27

Input of matrix row ends with -1, and input of matrix ends with -2. I need to store values of matrix without including -1 and -2, and to print them. I cannot skip elements while printing because I will use that matrix later in the code.

Example input:
1 2 -1
3 4 -1
5 6 -2
Output:
1 2
3 4
5 6

My code doesn't do what I'm trying to accomplish.

#include <stdio.h>
int main() {
    int i, j, m = 0, n = 0, a[100][100];
    for (i = 0; i < 100; i  ) {
        m  ;
        for (j = 0; j < 100; j  ) {
            scanf("%d", &a[i][j]);
            if (a[i][j] == -2) {
                a[i][j] = a[i][j--];
                break;
            }

        }
        if (a[i][j] == -2)
            break;
    }
    m  ;
    n = j / 2;
    for (i = 0; i < m; i  ) {
        for (j = 0; j < n; j  ) {
            printf("M", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

CodePudding user response:

After comparing aa[i] to -1 and -2 then store it to a[i];

If a[i] = -1, then n = nn[i].

n=n/(m-1).

Code:

#include <stdio.h>
int main() {
    int i, j, m = 0, nn = 0, n = 0, a[100][100], aa[100][100];
    for (i = 0; i < 100; i  ) {
        m  ;
        for (j = 0; j < 100; j  ) {
            scanf("%d", &aa[i][j]);
            if (aa[i][j] != -1 && aa[i][j] != -2) {
                a[i][j] = aa[i][j];
                nn  ;
            }
            if (aa[i][j] == -1) {
                n = nn;
                break;
            }
            if (aa[i][j] == -2) {
                break;
            }

        }
        if (aa[i][j] == -2)
            break;
    }
    n=n/(m-1);
    for (i = 0; i < m; i  ) {
        for (j = 0; j < n; j  ) {
            printf("M", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}
  •  Tags:  
  • Related