Count frequency of k in a matrix of size n where matrix(i, j) = i+j in C++

C++Server Side ProgrammingProgramming

We are given a matrix of integer values and the task is to calculate the count of the frequency of a given integer variable let’s say, k in the matrix. The size of a matrix can depend upon the size the user wants and in the below program we are taking it to be 4X4. Matrix will be formed on the given condition i.e matrix(i, j) will be i+j. The index value of the first data in a matrix will be 0 and 0 i.e. matrix[0][0] = 0.

Input − int size = 4, k = 4

Output − count of 4 in given matrix 4x4 is 3

Explanation

matrix[i][j] = i+j where i=j=4
Matrix[4][4] = {
   0, 1, 2, 3
   1, 2, 3, 4
   2, 3, 4, 5
   3, 4, 5, 6
}
The number k i.e. 4 is occurring 3 times in a matrix.

Input − int size = 3, k = 1

Output − count of 2 in given matrix 4x4 is 2

Explanation

matrix[i][j] = i+j where i=j=3
Matrix[3][3] = {
   0, 1, 2
   1, 2, 3
   2, 3, 4
}
The number k i.e. 1 is occurring 2 times in a given matrix.

Approach used in the below program is as follow

  • Input the size of a matrix of n x n and an integer value ‘k’ that will be searched in a matrix

  • Start the loop i from 0 till row size

  • Inside the loop start another loop j from 0 till column size

  • Set matrix[i][j] = i+j

  • Check IF matrix[i][j] = k

  • If yes, then increment the count by 1 else ignores the data.

  • Return the count

  • Print the result

Example

 Live Demo

#include <cmath>
#include <iostream>
using namespace std;
int count(int size, int k){
   int count = 0;
   int matrix[size][size];
   for(int i = 0;i<size;i++){
      for(int j=0; j<size; j++){
         matrix[i][j] = i+j;
         if(matrix[i][j] == k){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int size = 4;
   int k = 4;
   int total = count(size, k);
   if(total>0){
      cout<<"Count of frequency of "<<k<<" in a matrix of size "<<size<<"X"<<vsize<<" where matrix(i, j) = i+j is: "<<total;
   } else {
      cout<<"Frequency of element is 0 that means it is not present in a matrix";
   }
}

Output

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

Count of frequency of 4 in a matrix of size 4X4 where matrix(i, j) = i+j is: 3
raja
Published on 06-Jun-2020 11:58:40
Advertisements