How can matrix addition be implemented in the C language?

To add two matrices together, their number of rows and columns must be equal.

Here is an example code in C language for adding matrices.

#include <stdio.h>

#define ROWS 3
#define COLS 3

// 相加函数
void matrixAddition(int mat1[][COLS], int mat2[][COLS], int res[][COLS]) {
    int i, j;
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            res[i][j] = mat1[i][j] + mat2[i][j];
        }
    }
}

// 打印矩阵函数
void printMatrix(int mat[][COLS]) {
    int i, j;
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int mat1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int mat2[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int res[ROWS][COLS];

    printf("Matrix 1:\n");
    printMatrix(mat1);
    printf("Matrix 2:\n");
    printMatrix(mat2);

    matrixAddition(mat1, mat2, res);

    printf("Result:\n");
    printMatrix(res);

    return 0;
}

When running the code above, it will output:

Matrix 1:
1 2 3 
4 5 6 
7 8 9 
Matrix 2:
9 8 7 
6 5 4 
3 2 1 
Result:
10 10 10 
10 10 10 
10 10 10 

Here we have defined a function called matrixAddition, which takes two matrices and a result matrix as parameters. Inside the function, two nested loops are used to iterate over each element in the matrices and add them together, storing the result in the result matrix.

Then we defined a printMatrix function to print the matrix.

In the main function, we declared two input matrices mat1 and mat2, and defined a result matrix res. We then called the matrixAddition function to add mat1 and mat2, with the result stored in res. Finally, we used the printMatrix function to print the input matrices and the result matrix.

bannerAds