Matrix Addition using Arrays in C
Matrix addition in C is performed by adding corresponding elements of two matrices and storing the result in a third matrix. We use nested loops to iterate through the matrices and add the respective elements.
In this tutorial, we will cover different methods to implement matrix addition using arrays in C with detailed explanations and examples.
Examples of Matrix Addition in C
1. Matrix Addition of Two 2×2 Matrices
In this example, we will add two 2×2 matrices by adding corresponding elements and storing the result in a third matrix.
main.c
</>
Copy
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2]; // Resultant matrix
// Adding corresponding elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// Printing the result
printf("Resultant Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare two 2×2 matrices
A
andB
with predefined values. - A third matrix
C
is declared to store the sum of the corresponding elements. - We use nested
for
loops to iterate through the rows and columns. - Inside the loop, each element of
C[i][j]
is computed asA[i][j] + B[i][j]
. - Another loop prints the resultant matrix.
Output:
Resultant Matrix:
6 8
10 12
2. Matrix Addition of Two 3×3 Matrices with User Input
In this example, we take two 3×3 matrices as user input and perform matrix addition.
main.c
</>
Copy
#include <stdio.h>
int main() {
int A[3][3], B[3][3], C[3][3];
// Taking input for matrix A
printf("Enter elements of first 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &A[i][j]);
}
}
// Taking input for matrix B
printf("Enter elements of second 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &B[i][j]);
}
}
// Performing matrix addition
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// Displaying the resultant matrix
printf("Resultant Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare three 3×3 matrices:
A
,B
, andC
(for storing results). - Two loops are used to take user input for matrices
A
andB
. - A nested
for
loop performs matrix addition and stores the result inC
. - Another loop prints the resulting matrix
C
.
Output (Example Input & Output):
Enter elements of first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Enter elements of second 3x3 matrix:
9 8 7
3 3 4
1 1 1
Resultant Matrix:
10 10 10
7 8 10
8 9 10
Conclusion
In this tutorial, we learned how to perform matrix addition using arrays in C. The key takeaways are:
- Basic Matrix Addition: Using predefined matrices and nested loops.
- Matrix Addition with User Input: Accepting values from users and performing addition.