Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับรายการเท่ากับ x ในเมทริกซ์พิเศษใน C++


ให้เมทริกซ์สี่เหลี่ยมจัตุรัส mat[][] ที่ mat[i][j] = i*j งานคือนับจำนวนสมาชิกที่เท่ากับ x

เมทริกซ์คืออาร์เรย์ 2 มิติที่แสดงตัวเลขเป็นแถวและคอลัมน์

อินพุต − matrix = {{1,2,3},{3,4,3},{3,4,5}}, x = 3

เอาต์พุต − Count of entries equal to x in a special matrix: 4

อินพุต − matrix = {{10,20,30},{30,40,30},{30,40,50}}, x = 30

เอาต์พุต − Count of entries equal to x in a special matrix: 4

แนวทาง

  • รับเมทริกซ์และ x

  • วนลูปทั้งเมทริกซ์ นับที่ mat[i][j] == x

ตัวอย่าง

#include<bits/stdc++.h> 
using namespace std; 
#define row 3 
#define col 3 

int count(int matrix[row][col], int x){ 
    int count = 0; 
    for(int i = 0; i<row; i++) 
        for(int j = 0; j<col; j++) 
            if(matrix[i][j] == x) 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