Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หาผลรวมขอบเขตเมทริกซ์ (Boundary Elements Sum)

หาตัวเลขที่อยู่ขอบเมทริกซ์ (แถวแรก แถวสุดท้าย คอลัมน์แรก คอลัมน์สุดท้าย) และหาผลรวม

ตัวอย่าง

Given matrix:
1 2 3
4 5 6
7 8 9

Boundary matrix:
1 2 3
4   6
7 8 9
Sum = 1+2+3+4+6+7+8+9 = 40

ตรรกะ

if (i == 0 || j == 0 || i == m-1 || j == n-1) {
    // เป็น boundary element
    sum += mat[i][j];
}

โปรแกรม

#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 mat[m][n];
    printf("Input the matrix elements:\n");
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            scanf("%d", &mat[i][j]);
    printf("Boundary Matrix:\n");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0 || i == m-1 || j == n-1) {
                printf("%d ", mat[i][j]);
                sum += mat[i][j];
            } else {
                printf("  ");
            }
        }
        printf("\n");
    }
    printf("Sum of boundary is %d\n", sum);
    return 0;
}

ผลลัพธ์

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