打印二维矩阵中角元素及其总和的 C 程序。


给出大小为 2X2 的数组,目标是打印存储在数组中的所有角元素的总和。

假设一个矩阵 mat[r][c],其中有起始行和列为 0 的行列数“r”和“c”,则其角元素为;mat[0][0]、mat[0][c-1]、mat[r-1][0]、mat[r-1][c-1]。现在,任务是获取这些角元素并对这些角元素求和,即 mat[0][0] + mat[0][c-1] + mat[r-1][0] + mat[r-1][c-1],并打印屏幕上的结果。

示例

Input: Enter the matrix elements :
   10 2 10
   2 3 4
   10 4 10
Output: sum of matrix is : 40

算法

START
Step 1-> create macro for rows and column as #define row 3 and #define col 3
Step 2 -> main()
   Declare int sum=0 and array as a[row][col] and variables int i,j,n
   Loop For i=0 and i<3 and i++
      Loop For j=0 and j<3 and j++
         Input a[i][j]
      End
   End
   Print [0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1]
STOP

示例

#include<stdio.h>
#define row 3
#define col 3
int main(){
   int sum=0,a[row][col],i,j,n;
   printf("Enter the matrix elements : ");
   for(i=0;i<3;i++){
      for(j=0;j<3;j++){
         scanf("%d",&a[i][j]);
      }
   }
   printf("sum of matrix is : %d",a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] );
   return 0;
}

输出

如果我们运行上面的程序,它将产生以下输出

Enter the matrix elements :
10 2 10
2 3 4
10 4 10
sum of matrix is : 40

更新于:22-Aug-2019

2K+ 浏览

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.