# Count all sorted rows in a matrix in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to find the number of all sorted rows in a matrix.

For this we will be provided with m*n matrix. Our task is to count all the rows in the given matrix that are sorted either in ascending or descending order.

## Example

Live Demo

#include <bits/stdc++.h>
#define MAX 100
using namespace std;
//counting sorted rows
int count_srows(int mat[][MAX], int r, int c){
int result = 0;
for (int i=0; i<r; i++){
int j;
for (j=0; j<c-1; j++)
if (mat[i][j+1] <= mat[i][j])
break;
if (j == c-1)
result++;
}
for (int i=0; i<r; i++){
int j;
for (j=c-1; j>0; j--)
if (mat[i][j-1] <= mat[i][j])
break;
if (c > 1 && j == 0)
result++;
}
return result;
}
int main(){
int m = 4, n = 5;
int mat[][MAX] = {{1, 2, 3, 4, 5}, {  4, 3, 1, 2, 6}, {8, 7, 6, 5, 4}, {5, 7, 8, 9, 10}};
cout << count_srows(mat, m, n);
return 0;
}

## Output

3