# Count entries equal to x in a special matrix in C++

C++Server Side ProgrammingProgramming

Given a square matrix, mat[][] let the elements of the matrix me mat[i][j] = i*j, the task is to count the number of elements in the matrix is equal to x.

Matrix is like a 2d array in which numbers or elements are represented as rows and columns.

So, let's understand the solution of the problem with the help of examples −

Input

matrix[row][col] = {
{1, 2, 3},
{3, 4, 3},
{3, 4, 5}};
x = 3

Output

Count of entries equal to x in a special matrix: 4

Input

matrix[row][col] = {
{10, 20, 30},
{30, 40, 30},
{30, 40, 50}};
x = 30

Output

Count of entries equal to x in a special matrix: 4

## Approach used in the below program as follows

• Take a matrix mat[][] and x as the input values.

• In function count, we will count the number of entries.

• Traverse the whole matrix, where you find the value of mat[i][j] == x then increment the count by 1.

• Return the value of count and print it as a result.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
//count the entries equal to X
int count (int matrix[row][col], int x){
int count = 0;
// traverse and find the factors
for(int i = 0 ;i<row;i++){
for(int j = 0; j<col; j++){
if(matrix[i][j] == x){
count++;
}
}
}
// return count
return count;
}
int main(){
int matrix[row][col] = {
{1, 2, 3},
{3, 4, 3},
{3, 4, 5}
};
int x = 3;
cout<<"Count of entries equal to x in a special matrix: "<<count(matrix, x);
return 0;
}

## Output

If we run the above code we will get the following output −

Count of entries equal to x in a special matrix: 4