C 语言矩阵加法程序

如何编写 C 语言程序来相加两个矩阵或矩阵,或者如何编写程序通过示例执行两个多维数组的加法。

Mathematical Representation of Matrix Addition

C 语言矩阵加法程序

此矩阵加法程序允许用户输入两个矩阵的行数和列数。接下来,我们将使用 For 循环来相加这两个矩阵。

#include<stdio.h>
 
int main()
{
 	int i, j, rows, columns, a[10][10], b[10][10];
 	int arr[10][10];
  
 	printf("\n Please Enter Number of rows and columns  :  ");
 	scanf("%d %d", &i, &j);
 
 	printf("\n Please Enter the First Elements\n");
 	for(rows = 0; rows < i; rows++)
  	{
   		for(columns = 0; columns < j; columns++)
    	{
      		scanf("%d", &a[rows][columns]);
    	}
  	}
   
 	printf("\n Please Enter the Second Elements\n");
 	for(rows = 0; rows < i; rows++)
  	{
   		for(columns = 0; columns < j; columns++)
    	{
      		scanf("%d", &b[rows][columns]);
    	}
  	}
  
 	for(rows = 0; rows < i; rows++)
  	{
   		for(columns = 0; columns < j; columns++)
    	{
      		arr[rows][columns] = a[rows][columns] + b[rows][columns];    
   	 	}
  	}
 
 	printf("\n The Sum of Two a and b = a + b \n");
 	for(rows = 0; rows < i; rows++)
  	{
   		for(columns = 0; columns < j; columns++)
    	{
      		printf("%d \t ", arr[rows][columns]);
    	}
    	printf("\n");
  	}
 	return 0;
}
C Program to Add Two Matrices Example

在这个 C 语言矩阵加法程序中,我们声明了三个大小为 10*10 的二维数组:a、b 和 arr。

下面的语句要求用户输入矩阵 a、b 的大小(行数和列数)。例如,2 行 3 列 = a[2][3] 和 b[2][3])。

printf("\n Please Enter Number of rows and columns  :  ");
scanf("%d %d", &i, &j);

接下来,我们使用 for 循环遍历 a[2][3] 中的每个单元格。for 循环中的条件(rows < i)和(columns < j)将确保编程编译器不会超出矩阵的限制。否则,它将发生溢出。

for 循环中的 scanf 语句会将用户输入的数值存储到每个单独的数组元素中,例如 a[0][0]、a[0][1]、a[0][2]、a[1][0]、a[1][1]、a[1][2]。

接下来,C 语言矩阵加法程序中的 for 循环会将用户输入的数值存储到 b[2][3] 中。

在下一个程序行中,我们有另一个 for 循环来获取总和。

此矩阵加法示例的用户输入值如下:

a[2][3] = {{10, 20, 30}, { 40, 50, 60}}
b[2][3] = {{25, 35, 45}, { 55, 65, 75}}

矩阵加法程序 – 第一行迭代:for(rows = 0; rows < 2; 0++)
条件 (0 < 2) 为真。因此,它将进入第二个 for 循环。

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

第二个列迭代:for(columns = 1; 1 < 3; 1++)
此矩阵加法程序中的条件 (1 < 3) 为真。
arr [0][1]= a[0][1] + b[0][1]
arr [0][1]= 20 + 35 = 55

第二个列迭代:for(columns = 2; 2 < 3; 2++)
条件 (1 < 3) 为真。
arr [0][2] = a[0][2] + b[0][2]
arr [0][2]= 30 + 45 = 75

接下来,j 值将递增。递增后,第二个 for 循环中的条件(columns < 3)将失败。因此,它将退出循环。

现在,rows 的值将递增(rows 将变为 1),然后开始第二个行迭代。

请遵循相同的步骤,其中 rows = 1。最后,我们使用另一个 for 循环来打印相加后的矩阵。

评论已关闭。