정사각 행렬이 주어지면 mat[][] 행렬의 요소를 me mat[i][j] =i*j로 둡니다. 작업은 요소의 수를 계산하는 것입니다. 행렬은 x와 같습니다.
행렬은 숫자나 요소가 행과 열로 표현되는 2차원 배열과 같습니다.
따라서 예제의 도움으로 문제의 해결책을 이해합시다 -
입력 -
matrix[row][col] = {
{1, 2, 3},
{3, 4, 3},
{3, 4, 5}};
x = 3 출력 -
Count of entries equal to x in a special matrix: 4
입력 -
matrix[row][col] = {
{10, 20, 30},
{30, 40, 30},
{30, 40, 50}};
x = 30 출력 -
Count of entries equal to x in a special matrix: 4
아래 프로그램에서 사용하는 접근 방식은 다음과 같습니다.
-
행렬 mat[][] 및 x를 입력 값으로 사용합니다.
-
함수 수에서 항목 수를 계산합니다.
-
mat[i][j] ==x의 값을 찾은 전체 행렬을 탐색한 다음 카운트를 1씩 증가시킵니다.
-
count 값을 반환하고 결과로 출력합니다.
예시
#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;
} 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Count of entries equal to x in a special matrix: 4