ปัญหา
คำนวณผลรวมและผลคูณขององค์ประกอบทั้งหมดในอาร์เรย์ โดยใช้การคอมไพล์ระหว่างรัน
วิธีแก้
อาร์เรย์ 2 มิติ ใช้เมื่อต้องจัดเก็บตารางค่า หรือในการประยุกต์เมทริกซ์
ไวยากรณ์มีดังนี้:
datatype array_name [rowsize] [columnsize];
ตัวอย่าง: int a[5][5];
จำนวนองค์ประกอบ = rowsize * columnsize = 5*5 = 25
ตัวอย่าง
โปรแกรม C คำนวณผลรวมและผลคูณขององค์ประกอบในอาร์เรย์ 2x3 โดยใช้การคอมไพล์ระหว่างรัน:
#include <stdio.h>
void main() {
// ประกาศอาร์เรย์ - รันไทม์ //
int A[2][3], B[2][3], i, j, sum[2][3], product[2][3];
// อ่านองค์ประกอบเข้าไปในอาร์เรย์ A และ B โดยใช้ลูป for //
printf("Enter elements into the array A: \n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("A[%d][%d] :", i, j);
scanf("%d", &A[i][j]);
}
printf("\n");
}
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("B[%d][%d] :", i, j);
scanf("%d", &B[i][j]);
}
printf("\n");
}
// คำนวณผลรวมและพิมพ์เอาต์พุท //
printf("Sum array is : \n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
sum[i][j] = A[i][j] + B[i][j];
printf("%d\t", sum[i][j]);
}
printf("\n");
}
// คำนวณผลคูณและพิมพ์เอาต์พุท //
printf("Product array is : \n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
product[i][j] = A[i][j] * B[i][j];
printf("%d\t", product[i][j]);
}
printf("\n");
}
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
Enter elements into the array A: A[0][0] :12 A[0][1] :23 A[0][2] :03 A[1][0] :25 A[1][1] :34 A[1][2] :01 B[0][0] :03 B[0][1] :46 B[0][2] :23 B[1][0] :01 B[1][1] :24 B[1][2] :32 Sum array is: 15 69 26 26 58 33 Product array is: 36 1058 69 25 816 32