给定一个整数值矩阵,任务是计算给定整数变量的频率计数,比方说,矩阵中的k。矩阵的大小取决于用户所需的大小,在下面的程序中,我们将其设为4X4。矩阵将在给定条件下形成,即矩阵(i,j)将为i + j。矩阵中第一个数据的索引值为0和0,即matrix [0] [0] = 0。
输入-int大小= 4,k = 4
输出-给定矩阵4x4中4的计数为3
说明-
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.
输入-int大小= 3,k = 1
输出-给定矩阵4x4中2的计数为2
说明-
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.
输入nxn矩阵的大小和将在矩阵中搜索的整数值“ k”
从0到行大小开始循环i
在循环内部,从0到列大小开始另一个循环j
设置矩阵[i] [j] = i + j
检查IF矩阵[i] [j] = k
如果是,则将计数增加1,否则将忽略数据。
返回计数
打印结果
#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"; } }
输出结果
如果运行上面的代码,我们将获得以下输出-
Count of frequency of 4 in a matrix of size 4X4 where matrix(i, j) = i+j is: 3