Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matrix input ends with -1 and -2

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("%4d", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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("%4d", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading