จากเมทริกซ์ เราจำเป็นต้องพิมพ์องค์ประกอบขอบเขตของเมทริกซ์และแสดงผลรวมของเมทริกซ์
ตัวอย่าง
อ้างถึงเมทริกซ์ที่ระบุด้านล่าง -
เมทริกซ์ที่กำหนด
1 2 3 4 5 6 7 8 9
เมทริกซ์ขอบเขต
1 2 3 4 6 7 8 9
ผลรวมขององค์ประกอบขอบเขต:1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 =40
ตรรกะในการหาผลรวมของเมทริกซ์ขอบเขต เป็นดังนี้ −
for(i = 0; i<m; i++){
for(j = 0; j<n; j++){
if (i == 0 || j == 0 || i == n – 1 || j == n – 1){
printf("%d ", mat[i][j]);
sum = sum + mat[i][j];
}
else
printf(" ");
}
printf("\n");
} โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อ พิมพ์ผลรวมขององค์ประกอบขอบเขตของเมทริกซ์ −
#include<stdio.h>
#include<limits.h>
int main(){
int m, n, sum = 0;
printf("\nEnter the order of the matrix : ");
scanf("%d %d",&m,&n);
int i, j;
int mat[m][n];
printf("\nInput the matrix elements\n");
for(i = 0; i<m; i++){
for(j = 0; j<n; j++)
scanf("%d",&mat[i][j]);
}
printf("\nBoundary Matrix\n");
for(i = 0; i<m; i++){
for(j = 0; j<n; j++){
if (i == 0 || j == 0 || i == n – 1 || j == n – 1){
printf("%d ", mat[i][j]);
sum = sum + mat[i][j];
}
else
printf(" ");
}
printf("\n");
}
printf("\nSum of boundary is %d", sum);
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter the order of the matrix : 3 3 Input the matrix elements : 1 2 3 4 5 6 7 8 9 Boundary Matrix : 1 2 3 4 6 7 8 9 Sum of boundary is 40