C言語:2次元配列の行ごとの合計を求める方法

二次元配列の各行の合計を求めるには、各行をループして合計を取るために二重ループを使用することができます。以下はサンプルコードです:

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

この例では、最初に2次元配列の行数と列数を入力し、次に配列の要素を入力します。そして、2重ループを使用して各行を走査し、各行の合計を計算し、最後に各行の合計を出力します。

bannerAds