Easy Tutorial
❮ C Examples Fibonacci Series C Function Rewind ❯

C Language Example - Adding Two Matrices

C Language Examples

Adding two matrices using a multidimensional array.

Example

#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 (1 ~ 100): ");
    scanf("%d", &r);
    printf("Enter the number of columns (1 ~ 100): ");
    scanf("%d", &c);

    printf("\nEnter elements of the first matrix:\n");

    for(i=0; i&lt;r; ++i)
        for(j=0; j&lt;c; ++j)
        {
            printf("Enter element a%d%d: ",i+1,j+1);
            scanf("%d",&a[i][j]);
        }

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

    // Adding matrices

    for(i=0;i&lt;r;++i)
        for(j=0;j&lt;c;++j)
        {
            sum[i][j]=a[i][j]+b[i][j];
        }

    // Displaying the result
    printf("\nSum of the matrices: \n\n");

    for(i=0;i&lt;r;++i)
        for(j=0;j&lt;c;++j)
        {

            printf("%d   ",sum[i][j]);

            if(j==c-1)
            {
                printf("\n\n");
            }
        }

    return 0;
}

Output:

Enter the number of rows (1 ~ 100): 2
Enter the number of columns (1 ~ 100): 3

Enter elements of the first 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 the second 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 the matrices: 

-2   8   7   

10   8   6

C Language Examples

❮ C Examples Fibonacci Series C Function Rewind ❯