Introduction
Matrix addition is a fundamental operation in linear algebra where two matrices of the same dimensions are added together by adding their corresponding elements. This operation is commonly used in various applications, including computer graphics, simulations, and scientific computations.
#include <stdio.h>
#define MAX_SIZE 10 // Define maximum size for the matrices
void addMatrices(int a[MAX_SIZE][MAX_SIZE], int b[MAX_SIZE][MAX_SIZE], int result[MAX_SIZE][MAX_SIZE], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j]; // Add corresponding elements
}
}
}
int main() {
int a[MAX_SIZE][MAX_SIZE], b[MAX_SIZE][MAX_SIZE], result[MAX_SIZE][MAX_SIZE];
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("a[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("b[%d][%d]: ", i, j);
scanf("%d", &b[i][j]);
}
}
addMatrices(a, b, result, rows, cols);
printf("Resultant matrix after addition:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
- Function Definition:
addMatrices(int a[MAX_SIZE][MAX_SIZE], int b[MAX_SIZE][MAX_SIZE], int result[MAX_SIZE][MAX_SIZE], int rows, int cols)
: This function takes two input matrices (a
andb
), an empty matrix (result
) to store the sum, and the number of rows and columns.
- Loop:
- Nested
for
loops iterate over each element of the matrices. For each element at position(i, j)
, the corresponding elements of matricesa
andb
are added and stored inresult
.
- Nested
- Main Function:
- Prompts the user for the dimensions of the matrices.
- Accepts the elements for both matrices from user input.
- Calls
addMatrices
to perform the addition. - Prints the resultant matrix.
Input
When you run the program, it will ask for the number of rows and columns, followed by the elements of each matrix. For example:
Enter the number of rows and columns: 2 2
Enter elements of the first matrix:
a[0][0]: 1
a[0][1]: 2
a[1][0]: 3
a[1][1]: 4
Enter elements of the second matrix:
b[0][0]: 5
b[0][1]: 6
b[1][0]: 7
b[1][1]: 8
Output
The output will display the resultant matrix after addition:
Resultant matrix after addition:
6 8
10 12
Conclusion
Matrix addition is a simple yet essential operation in many mathematical and engineering applications. The provided C implementation allows for easy addition of two matrices of the same dimensions. With a straightforward approach, this program effectively demonstrates how to manipulate and compute with matrices, highlighting the basics of array handling in C.