-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest3.cpp
More file actions
59 lines (52 loc) · 1.37 KB
/
test3.cpp
File metadata and controls
59 lines (52 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
using namespace std;
int** keepEven(int** matrix, int nRows, int nCols) {
// Bước 1: Tạo ma trận mới
int** newMatrix = new int*[nRows];
for (int i = 0; i < nRows; ++i) {
newMatrix[i] = new int[nCols];
}
// Bước 2: Duyệt qua từng phần tử
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
if (*(*(matrix+i)+j) % 2 == 0) {
newMatrix[i][j] = matrix[i][j];
} else {
newMatrix[i][j] = 0;
}
}
}
// Bước 3: Trả về ma trận mới
return newMatrix;
}
int main() {
int nRows , nCols;
cin>>nRows>>nCols;
int** matrix = new int*[nRows];
for (int i = 0; i < nRows; ++i) {
matrix[i] = new int[nCols];
}
// Nhập ma trận
for (int i=0;i<nRows;i++){
for (int j=0;j<nCols;j++){
cin>>matrix[i][j];
}
}
// Gọi hàm keepEven
int** newMatrix = keepEven(matrix, nRows, nCols);
// In ra ma trận mới
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
cout << newMatrix[i][j] << " ";
}
cout << endl;
}
// Giải phóng vùng nhớ
for (int i = 0; i < nRows; ++i) {
delete[] matrix[i];
delete[] newMatrix[i];
}
delete[] matrix;
delete[] newMatrix;
return 0;
}