首頁  >  文章  >  後端開發  >  印出矩陣邊界元素總和的C程序

印出矩陣邊界元素總和的C程序

WBOY
WBOY轉載
2023-09-15 15:53:021112瀏覽

印出矩陣邊界元素總和的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 &ndash; 1 || j == n &ndash; 1){
         printf("%d ", mat[i][j]);
         sum = sum + mat[i][j];
      }
      else
         printf(" ");
      }
      printf("</p><p>");
}

程式

#以下是用於列印矩陣邊界元素總和的C程式-

#include<stdio.h>
#include<limits.h>
int main(){
   int m, n, sum = 0;
   printf("</p><p>Enter the order of the matrix : ");
   scanf("%d %d",&m,&n);
   int i, j;
   int mat[m][n];
   printf("</p><p>Input the matrix elements</p><p>");
   for(i = 0; i<m; i++){
      for(j = 0; j<n; j++)
      scanf("%d",&mat[i][j]);
   }
   printf("</p><p>Boundary Matrix</p><p>");
   for(i = 0; i<m; i++){
      for(j = 0; j<n; j++){
         if (i == 0 || j == 0 || i == n &ndash; 1 || j == n &ndash; 1){
            printf("%d ", mat[i][j]);
            sum = sum + mat[i][j];
         }
         else
         printf(" ");
      }
      printf("</p><p>");
   }
   printf("</p><p>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

以上是印出矩陣邊界元素總和的C程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除