列印二維矩陣中角元素及其總和的 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
廣告