C 语言查找矩阵每行之和的程序

编写一个 C 程序来查找矩阵中每行的总和。或者如何编写一个 C 程序来计算多维数组中行的总和,并附带示例。

C 语言查找矩阵每行之和的程序 示例 1

此程序允许您输入矩阵的总行数和列数。接下来,我们将使用 For 循环计算矩阵行的总和。

/* C Program to find Sum of rows in a Matrix  */

#include<stdio.h>
 
int main()
{
    int i, j, rows, columns, a[10][10], Sum;
    
    printf("Please Enter Number of rows and columns  :  ");
    scanf("%d %d", &i, &j);
    
    printf("Please Enter the Matrix Row and Column Elements \n");
    for(rows = 0; rows < i; rows++)
    {
        for(columns = 0; columns < j; columns++)
        {
            scanf("%d", &a[rows][columns]);
        }
    }
    
    for(rows = 0; rows < i; rows++)
    {
        Sum = 0;
        for(columns = 0; columns < j; columns++)
        {
            Sum = Sum + a[rows][columns];
        }
        printf("The Sum of Elements of a Rows in a Matrix =  %d \n", Sum );
    }
    
    return 0;
}
C Program to find Sum of each row in a Matrix

在这个 C 语言查找矩阵每行之和的程序中,我们声明了一个大小为 10 * 10 的二维数组。接下来,printf 语句会提示用户输入矩阵大小(行和列。例如 3 行,3 列 = a[3][3])

接下来,我们使用 for 循环 遍历 a[3][3] 矩阵中的每个单元格。for 循环内的 scanf 语句会将用户输入的数值存储在每个单独的数组元素中,例如 a[0][0],a[0][1],……。

在此 C 语言查找矩阵每行之和的演示中,用户输入的数值为:a[3][3] = {{10, 20, 30}, { 12, 22, 32}, {44, 55, 121}}

行第一次迭代: for(rows = 0; rows < 3; 0++)
条件 (0 < 3) 为 True。
Sum = 0

列第一次迭代: for(columns = 0; 0 < 3; 0++)
条件 (0 < 3) 为 True。因此,它将开始执行循环内的语句
Sum  = Sum + a[rows][columns]
Sum  = Sum + a[0][0] => 0 + 10 = 10

列第二次迭代: for(columns = 1; 1 < 3; 1++) – 条件为 True
Sum  = Sum + a[0][1] => 10 + 20 = 30

列第三次迭代: for(columns = 2; 2 < 3; 2++) – 条件为 True
Sum  = Sum + a[0][2] => 30 + 30 = 60

接下来,列的值将增加到 4。条件 (columns < 3) 将失败。因此,它将退出循环。

接下来,我们使用 C 语言的 Printf 语句打印 Sum。在此之后,rows 的值将增加到 1,Sum 将变为 0。

对 rows = 1 和 rows = 2 重复上述步骤

查找矩阵每行之和 示例 2

这个 C 程序与上面相同,但这次我们使用 函数 将代码分开。

/* C Program to find Sum of rows in a Matrix  */

#include<stdio.h>

void addRows(int arr[10][10], int i, int j)
{
    int rows, columns;
    for(rows = 0; rows < i; rows++)
    {
        int Sum = 0;
        for(columns = 0; columns < j; columns++)
        {
            Sum = Sum + arr[rows][columns];
        }
        printf("The Sum of Elements of a Rows in a Matrix =  %d \n", Sum );
    }
}
int main()
{
    int i, j, rows, columns, a[10][10];
    
    printf("Please Enter Number of rows and columns  :  ");
    scanf("%d %d", &i, &j);
    
    printf("Please Enter the Matrix Row and Column Elements \n");
    for(rows = 0; rows < i; rows++)
    {
        for(columns = 0; columns < j; columns++)
        {
            scanf("%d", &a[rows][columns]);
        }
    }
    
    addRows(a, i, j);
    
    return 0;
}
Please Enter Number of rows and columns  :  3 3
Please Enter the Matrix Row and Column Elements 
10 20 30
40 50 760
70 80 90
The Sum of Elements of a Rows in a Matrix =  60 
The Sum of Elements of a Rows in a Matrix =  850 
The Sum of Elements of a Rows in a Matrix =  240