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

In phần tử góc và tổng của chúng trong ma trận 2D trong C

Cho ma trận 3x3, tính tổng 4 phần tử góc: a[0][0] + a[0][2] + a[2][0] + a[2][2].

Ví dụ

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

In phần tử góc và tổng của chúng trong ma trận 2D trong C

Thuật toán

BẮT ĐẦU
#define row 3, #define col 3
MAIN()
    NHẬP MA TRẬN a[row][col]
    TÍNH sum = a[0][0] + a[0][row-1] + a[col-1][0] + a[col-1][row-1]
    IN sum
KẾT THÚC

Chương trình C ví dụ

#include <stdio.h>
#define row 3
#define col 3

int main() {
    int sum = 0, a[row][col], i, j;
    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;
}

Kết quả

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