# C 程序：使用多维数组相加两个矩阵

> 原文： [https://www.programiz.com/c-programming/examples/add-matrix](https://www.programiz.com/c-programming/examples/add-matrix)

#### 在此示例中，您将学习使用二维数组在 C 编程中相加两个矩阵。

要理解此示例，您应该了解以下 [C 编程](/c-programming "C tutorial")主题：

*   [C 数组](/c-programming/c-arrays)
*   [C 多维数组](/c-programming/c-multi-dimensional-arrays)

* * *

## 相加两个矩阵的程序

```c
#include <stdio.h>
int main() {
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;
    printf("Enter the number of rows (between 1 and 100): ");
    scanf("%d", &r);
    printf("Enter the number of columns (between 1 and 100): ");
    scanf("%d", &c);

    printf("\nEnter elements of 1st matrix:\n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }

    printf("Enter elements of 2nd matrix:\n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &b[i][j]);
        }

    // adding two matrices
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            sum[i][j] = a[i][j] + b[i][j];
        }

    // printing the result
    printf("\nSum of two matrices: \n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("%d   ", sum[i][j]);
            if (j == c - 1) {
                printf("\n\n");
            }
        }

    return 0;
} 
```

**输出**

```c
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a13: 3
Enter element a21: 5
Enter element a22: 6
Enter element a23: 3

Sum of two matrices: 
-2   8   7   

10   8   6 
```

在此程序中，要求用户输入行数`r`和列数`c`。 然后，要求用户输入两个矩阵的元素（顺序`r*c`）。

然后，我们添加了两个矩阵的对应元素，并将其保存在另一个矩阵（二维数组）中。 最后，结果打印在屏幕上。