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

   2024-11-04 7720
核心提示:要求二维数组每行的和,可以使用双重循环来遍历每一行并求和。以下是一个示例代码:#include stdio.hint main() {int rows, cols

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

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

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

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号