Add 2 matrix in C
×


Add 2 matrix in C

37

Adding two matrices in C involves a fundamental operation in programming: element-wise addition.

 Each element of the resultant matrix is the sum of the corresponding elements of the input matrices.

This process is particularly useful in various computational tasks, including image processing, numerical simulations, and scientific computing.

To add two matrices in C, you need to ensure that both matrices have the same dimensions, meaning they have the same number of rows and columns.

This requirement is essential for performing element-wise addition, as each element in one matrix should correspond to the respective element in the other matrix.

Here's how the addition operation works for two matrices A and B:

Example:

// Program to add 2 Matrices in C
#include<stdio.h> 

int main() {
    int R, C;

    printf("Enter rows and columns: ");
    scanf("%d %d", &R, &C);

    int X[R][C], Y[R][C], Z[R][C];

    printf("Enter matrix X:\n");
    for (int N = 0; N < R; N++)
        for (int H = 0; H < C; H++)
            scanf("%d", &X[N][H]);

    // Input of matrix Y
    printf("Enter of matrix Y:\n");
    for (int N = 0; N < R; N++)
        for (int H = 0; H < C; H++)
            scanf("%d", &Y[N][H]);

    // Adding elements of matrices X and Y
    for (int N = 0; N < R; N++)
        for (int H = 0; H < C; H++)
            Z[N][H] = X[N][H] + Y[N][H];

    
    printf("\nSum (X + Y):\n");
    for (int N = 0; N < R; N++) {
        for (int H = 0; H < C; H++)
            printf("%d ", Z[N][H]);
        printf("\n");
    }
    return 0;
}

Output:

Enter rows and columns: 2
2
Enter matrix X:
3
4
5
6
Enter of matrix Y:
5
6
7
8

Sum (X + Y):
8 10 
12 14 


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments