溫馨提示×

C語言二維數組每行求和的方法是什么

小億
516
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女