Mảng là nhóm các mục dữ liệu liên quan lưu trữ dưới một tên duy nhất.
Ví dụ: int student[30];
Các thao tác trên mảng
- Tìm kiếm - Kiểm tra phần tử tồn tại.
- Sắp xếp - Sắp xếp tăng/giảm dần.
- Duyệt - Xử lý từng phần tử theo thứ tự.
- Chèn - Thêm phần tử.
- Xóa - Xóa phần tử.
Logic phép toán trên mảng 2 chiều
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
add[row][col] = A[row][col] + B[row][col];
sub[row][col] = A[row][col] - B[row][col];
mul[row][col] = A[row][col] * B[row][col];
div[row][col] = A[row][col] / B[row][col];
mod[row][col] = A[row][col] % B[row][col];
}
}
Logic in kết quả
printf("\nAdd\tSub\tMul\tDiv\tMod\n");
printf("-------------------------------\n");
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
printf("\n%d\t", add[row][col]);
printf("%d\t", sub[row][col]);
printf("%d\t", mul[row][col]);
printf("%.2f\t", div[row][col]);
printf("%d\t", mod[row][col]);
}
}
Chương trình hoàn chỉnh
#include <stdio.h>
int main() {
int i, j, row, col;
int A[20][20], B[20][20];
int add[10][10], sub[10][10], mul[10][10], mod[10][10];
float div[10][10];
printf("Nhập số hàng và cột:\n");
scanf("%d %d", &i, &j);
printf("Nhập mảng thứ 1:\n");
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
scanf("%d", &A[row][col]);
}
}
printf("Nhập mảng thứ 2:\n");
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
scanf("%d", &B[row][col]);
}
}
// Thực hiện các phép toán
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
add[row][col] = A[row][col] + B[row][col];
sub[row][col] = A[row][col] - B[row][col];
mul[row][col] = A[row][col] * B[row][col];
div[row][col] = (float)A[row][col] / B[row][col];
mod[row][col] = A[row][col] % B[row][col];
}
}
// In kết quả
printf("\nAdd\tSub\tMul\tDiv\tMod\n");
printf("-------------------------------\n");
for(row = 0; row < i; row++) {
for(col = 0; col < j; col++) {
printf("\n%d\t%d\t%d\t%.2f\t%d\t",
add[row][col], sub[row][col], mul[row][col],
div[row][col], mod[row][col]);
}
}
return 0;
}
Kết quả chạy
Nhập số hàng và cột: 3 4
Nhập mảng thứ 1: 1 2 4 5 6 7 3 8 3 2 1 8
Nhập mảng thứ 2: 1 2 1 2 1 3 4 2 1 2 1 1
Add Sub Mul Div Mod
-------------------------------
2 0 1 1.00 0
4 0 4 1.00 0
5 3 4 4.00 0
7 3 10 2.00 1
7 5 6 6.00 0
10 4 21 2.00 1
7 -1 12 0.00 3
10 6 16 4.00 0
4 2 3 3.00 0
4 0 4 1.00 0
2 0 1 1.00 0
9 7 8 8.00 0