C 語言程式,用於列印矩陣邊界元素的總和
給定一個矩陣,我們需要列印矩陣的邊界元素並顯示其總和。
示例
請參考以下給定的矩陣 −
給定矩陣
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("
");
}程式
以下是列印矩陣邊界元素總和的 C 語言程式 −
#include<stdio.h>
#include<limits.h>
int main(){
int m, n, sum = 0;
printf("
Enter the order of the matrix : ");
scanf("%d %d",&m,&n);
int i, j;
int mat[m][n];
printf("
Input the matrix elements
");
for(i = 0; i<m; i++){
for(j = 0; j<n; j++)
scanf("%d",&mat[i][j]);
}
printf("
Boundary Matrix
");
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("
");
}
printf("
Sum 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP