Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C in tổng các phần tử biên của ma trận

Cho một ma trận, cần in các phần tử biên (boundary elements) và hiển thị tổng của chúng.

Ví dụ

Tham chiếu ma trận dưới đây:

Ma trận cho trước

1 2 3 4 5 6 7 8 9

Ma trận biên

1 2 3 4   6 7 8 9

Tổng các phần tử biên: 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 = 40

Logic tìm tổng ma trận biê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"); }

Chương trình

Chương trình C in tổng các phần tử biên của ma trận:

#include  #include  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); }

Kết quả

Khi chạy chương trình:

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