Matrix – Count Sorted Rows

The program must accept an integer matrix of size RxC as the input. The program must print the number of rows containing the integers in ascending order in the matrix.

Boundary Condition(s):
3 <= R, C <= 50

Input Format:
The first line contains R and C separated by a space. The next R lines each contain C integers separated by a space.

Output Format:
The first line contains the number of rows containing the integers in ascending order in the matrix.

Example Input/Output 1:
Input:
4 5
4 6 7 8 19
1 3 5 7 8
3 5 6 12 6
5 7 8 9 13

Output:
3
Explanation:
In the 4×5 matrix, the integers in the first row, the second row, and the fourth row are sorted in ascending order.
First Row: 4, 6, 7, 8, 19
Second Row: 1, 3, 5, 7, 8
Fourth Row: 5, 7, 8, 9, 13
Hence the output is 3.

Example Input/Output 2:
Input:
3 3
37 68 79
65 52 31
56 79 25

Output:
1

#include <stdio.h>
#include <stdlib.h>

int main() {
    int r, c;
    scanf("%d %d", &r, &c);
    int a[r][c];

    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    int s = 0;
    for (int i = 0; i < r; i++) {
        int ascending = 1; // Flag to check if the row is in ascending order
        for (int j = 0; j < c - 1; j++) {
            if (a[i][j] > a[i][j + 1]) {
                ascending = 0;
                break;
            }
        }
        if (ascending) {
            s++;
        }
    }

    printf("%d", s);
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

More posts. You may also be interested in.