温馨提示×

C语言二维数组每行求和的方法是什么

小亿
263
2024-02-26 13:03:26
栏目: 编程语言

要求二维数组每行的和,可以使用双重循环来遍历每一行并求和。以下是一个示例代码:

#include <stdio.h>

int main() {
    int rows, cols;
    
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    int arr[rows][cols];
    
    // Input values into the array
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &arr[i][j]);
        }
    }
    
    // Calculate the sum of each row
    for (int i = 0; i < rows; i++) {
        int sum = 0;
        for (int j = 0; j < cols; j++) {
            sum += arr[i][j];
        }
        printf("Sum of row %d: %d\n", i+1, sum);
    }

    return 0;
}

在这个示例中,我们首先输入二维数组的行数和列数,然后输入数组的元素。接着使用双重循环遍历每一行并计算每行的和,最后输出每行的和。

0