溫馨提示×

c語言二維數(shù)組行列求和的方法是什么

小億
128
2024-05-31 18:28:12
欄目: 編程語言

在C語言中,可以通過嵌套循環(huán)來遍歷二維數(shù)組,并對每行和每列進(jìn)行求和操作。以下是一個示例代碼來實現(xiàn)二維數(shù)組行列求和:

#include <stdio.h>

int main() {
    int rows, cols;
    printf("Enter the number of rows and columns of the array: ");
    scanf("%d %d", &rows, &cols);

    int arr[rows][cols];
    printf("Enter the elements of the array:\n");

    // Input elements of the array
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            scanf("%d", &arr[i][j]);
        }
    }

    // Calculate row sums
    printf("Row sums:\n");
    for(int i = 0; i < rows; i++) {
        int sum = 0;
        for(int j = 0; j < cols; j++) {
            sum += arr[i][j];
        }
        printf("Row %d sum: %d\n", i+1, sum);
    }

    // Calculate column sums
    printf("Column sums:\n");
    for(int j = 0; j < cols; j++) {
        int sum = 0;
        for(int i = 0; i < rows; i++) {
            sum += arr[i][j];
        }
        printf("Column %d sum: %d\n", j+1, sum);
    }

    return 0;
}

在上面的代碼中,首先用戶輸入二維數(shù)組的行數(shù)和列數(shù),然后輸入數(shù)組的元素。接著分別計算每行和每列的和,并輸出結(jié)果。

0