c语言

c语言二维数组行列求和的方法是什么

小亿
128
2024-05-31 18:28:12
栏目: 编程语言

在C语言中,可以通过嵌套循环来遍历二维数组,并对每行和每列进行求和操作。以下是一个示例代码来实现二维数组行列求和:

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

在上面的代码中,首先用户输入二维数组的行数和列数,然后输入数组的元素。接着分别计算每行和每列的和,并输出结果。

0
看了该问题的人还看了