Array (อาร์เรย์) คือกลุ่มข้อมูลที่เกี่ยวข้องกัน เก็บภายใต้ชื่อเดียว
การดำเนินการกับ Array
- Searching - ค้นหาข้อมูล
- Sorting - เรียงลำดับ
- Traversing - เข้าถึงทุกข้อมูล
- Inserting - เพิ่มข้อมูล
- Deleting - ลบข้อมูล
ตรรกะการคำนวณคณิตศาสตร์บน 2D Array
for(row = 0; row < rows; row++) {
for(col = 0; col < cols; 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];
}
}
โปรแกรมตัวอย่าง
#include <stdio.h>
int main() {
int rows, cols, 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("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
printf("Enter 1st array elements:\n");
for(row = 0; row < rows; row++)
for(col = 0; col < cols; col++)
scanf("%d", &A[row][col]);
printf("Enter 2nd array elements:\n");
for(row = 0; row < rows; row++)
for(col = 0; col < cols; col++)
scanf("%d", &B[row][col]);
// คำนวณ
for(row = 0; row < rows; row++) {
for(col = 0; col < cols; 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];
}
}
// แสดงผล
printf("\nAdd\tSub\tMul\tDiv\tMod\n");
printf("-------------------------------\n");
for(row = 0; row < rows; row++) {
for(col = 0; col < cols; col++) {
printf("%d\t%d\t%d\t%.2f\t%d\n",
add[row][col], sub[row][col], mul[row][col],
div[row][col], mod[row][col]);
}
}
return 0;
}
ผลลัพธ์
enter no: of rows and columns: 3 4 enter elements of 1st array: 1 2 4 5 6 7 3 8 3 2 1 8 enter elements of 2nd array: 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