C Program to perform Matrix Addition

Last Updated:

Perform Matrix Addition

In the following example, we will add the two given matrices (two-dimensional arrays).

Example

C Compiler
#include <stdio.h> int main() { int i, j; int arr1[3][3] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; int arr2[3][3] = { {2, 2, 2}, {2, 2, 2}, {2, 2, 2} }; int arr3[3][3]; printf("\nMatrix A (3 x 3):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr1[i][j]); printf("\n"); } printf("\nMatrix B (3 X 3):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr2[i][j]); printf("\n"); } printf("\nMatrix Additon (A + B):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { arr3[i][j] = arr1[i][j] + arr2[i][j]; printf("%d ", arr3[i][j]); } printf("\n"); } return 0; }

In the following example, we will get the values for (3 x 3) Matrices A and B from the user and display the matrix addition.

Example

C Compiler
#include <stdio.h> int main() { int i, j; int arr1[3][3], arr2[3][3], arr3[3][3]; printf("Enter Matrix A (3 X 3):\n"); for(i=0; i<3; i++) for(j=0; j<3; j++) scanf("%d", &arr1[i][j]); printf("\nEnter Matrix B (3 X 3):\n"); for(i=0; i<3; i++) for(j=0; j<3; j++) scanf("%d", &arr2[i][j]); printf("\nMatrix Additon (A + B):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { arr3[i][j] = arr1[i][j] + arr2[i][j]; printf("%d ", arr3[i][j]); } printf("\n"); } return 0; }

Share this Page

Meet the Author