Matrix Addition, Subtraction and Multiplication using 2D Arrays
Objective
To implement a C program that performs Addition, Subtraction, and Multiplication of two matrices
using two-dimensional arrays.
Materials Required
- Computer with a C compiler (like GCC)
- Text editor or IDE (e.g., Code::Blocks, Dev C++, Turbo C)
Source Code (C Language)
#include <stdio.h>
#define SIZE 10
void inputMatrix(int matrix[SIZE][SIZE], int row, int col) {
printf("Enter elements:\n");
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
scanf("%d", &matrix[i][j]);
void displayMatrix(int matrix[SIZE][SIZE], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
}
void addMatrices(int a[SIZE][SIZE], int b[SIZE][SIZE], int res[SIZE][SIZE], int row, int col) {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
res[i][j] = a[i][j] + b[i][j];
void subtractMatrices(int a[SIZE][SIZE], int b[SIZE][SIZE], int res[SIZE][SIZE], int row, int col) {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
res[i][j] = a[i][j] - b[i][j];
void multiplyMatrices(int a[SIZE][SIZE], int b[SIZE][SIZE], int res[SIZE][SIZE], int row1, int col1, int
col2) {
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
res[i][j] = 0;
for (int k = 0; k < col1; k++)
res[i][j] += a[i][k] * b[k][j];
int main() {
int a[SIZE][SIZE], b[SIZE][SIZE], result[SIZE][SIZE];
int row1, col1, row2, col2;
printf("Enter rows and columns for Matrix A: ");
scanf("%d %d", &row1, &col1);
printf("Enter rows and columns for Matrix B: ");
scanf("%d %d", &row2, &col2);
printf("Matrix A:\n");
inputMatrix(a, row1, col1);
printf("Matrix B:\n");
inputMatrix(b, row2, col2);
if (row1 == row2 && col1 == col2) {
addMatrices(a, b, result, row1, col1);
printf("Addition of matrices:\n");
displayMatrix(result, row1, col1);
subtractMatrices(a, b, result, row1, col1);
printf("Subtraction of matrices:\n");
displayMatrix(result, row1, col1);
} else {
printf("Addition/Subtraction not possible: Dimensions do not match.\n");
if (col1 == row2) {
multiplyMatrices(a, b, result, row1, col1, col2);
printf("Multiplication of matrices:\n");
displayMatrix(result, row1, col2);
} else {
printf("Multiplication not possible: Column of A != Row of B.\n");
return 0;
Conclusion
This microproject demonstrates the use of 2D arrays for performing basic matrix operations. It
strengthens understanding of nested loops and array manipulation, which are fundamental in
programming and matrix algebra.