C Program For Addition Of Two Matrix Using Array
Matrix addition is a fundamental operation in linear algebra, widely used in various computational fields. In this article, you will learn how to implement a C program to perform the addition of two matrices using arrays, covering the essential steps and providing a clear, runnable example.
Problem Statement
The core problem is to add two matrices, say matrix A and matrix B, and store their sum in a third matrix, matrix C. For matrix addition to be possible, both matrices must have the same number of rows and columns. The addition is performed element-wise, meaning that the element at row i, column j of matrix A is added to the element at row i, column j of matrix B, and the result is stored at row i, column j of matrix C.
For example, given two 2x2 matrices: $$ A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} $$ $$ B = \begin{pmatrix} 5 & 6 \\ 7 & 8 \end{pmatrix} $$ Their sum, matrix C, would be: $$ C = A + B = \begin{pmatrix} 1+5 & 2+6 \\ 3+7 & 4+8 \end{pmatrix} = \begin{pmatrix} 6 & 8 \\ 10 & 12 \end{pmatrix} $$
Example
Consider two 2x2 matrices: Matrix 1:
1 2
3 4
Matrix 2:
5 6
7 8
Their sum would be:
6 8
10 12
Background & Knowledge Prerequisites
To understand and implement matrix addition in C, you should have a basic understanding of:
- C Language Basics: Variables, data types, input/output operations (
printf,scanf). - Arrays: How to declare and access elements in one-dimensional and multi-dimensional arrays (specifically 2D arrays).
- Loops:
forloops for iterating over array elements.
Use Cases or Case Studies
Matrix addition is a foundational operation with applications across numerous domains:
- Image Processing: Images can be represented as matrices of pixel values. Adding matrices can be used for blending images, adjusting brightness, or applying filters.
- Computer Graphics: In 3D graphics, matrices are used for transformations (translation, rotation, scaling). Adding matrices can combine multiple transformations or adjust object positions.
- Data Analysis and Machine Learning: Datasets are often represented as matrices. Matrix addition might be used in operations like combining feature sets, updating weights in neural networks, or processing large datasets.
- Physics and Engineering Simulations: Many physical phenomena, like stress analysis, fluid dynamics, or structural analysis, use matrix operations to solve systems of equations or model behavior.
- Financial Modeling: In finance, matrices can represent portfolio data, transaction records, or economic models. Matrix addition might be used to aggregate financial data or combine different financial scenarios.
Solution Approaches
The most common and straightforward approach for matrix addition is using nested loops to iterate through each element.
Approach 1: Direct Addition using Nested Loops
This approach involves iterating through each row and each column of the matrices, adding corresponding elements, and storing the result in a new matrix.
- One-line summary: Use nested
forloops to traverse both input matrices simultaneously, performing element-wise addition into a result matrix.
// Matrix Addition using Arrays
#include <stdio.h>
int main() {
int rows, cols;
// Step 1: Get matrix dimensions from the user
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare three 2D arrays (matrices)
int matrix1[rows][cols];
int matrix2[rows][cols];
int sumMatrix[rows][cols];
// Step 2: Input elements for the first matrix
printf("\\nEnter elements for Matrix 1:\\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// Step 3: Input elements for the second matrix
printf("\\nEnter elements for Matrix 2:\\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Step 4: Perform matrix addition
// Iterate through each element and add corresponding elements
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Step 5: Display the result (sumMatrix)
printf("\\nSum of the matrices:\\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\\t", sumMatrix[i][j]);
}
printf("\\n"); // Move to the next line after each row
}
return 0;
}
- Sample output:
Enter the number of rows: 2 Enter the number of columns: 2 Enter elements for Matrix 1: Enter element matrix1[0][0]: 1 Enter element matrix1[0][1]: 2 Enter element matrix1[1][0]: 3 Enter element matrix1[1][1]: 4 Enter elements for Matrix 2: Enter element matrix2[0][0]: 5 Enter element matrix2[0][1]: 6 Enter element matrix2[1][0]: 7 Enter element matrix2[1][1]: 8 Sum of the matrices: 6 8 10 12
- Stepwise explanation for clarity:
- Get Dimensions: The program first prompts the user to enter the number of rows and columns for the matrices. These dimensions are used to declare the 2D arrays (matrices).
- Declare Matrices: Three 2D integer arrays (
matrix1,matrix2,sumMatrix) are declared using the providedrowsandcols. In C, these are often referred to as arrays of arrays. - Input Elements: Two sets of nested
forloops are used. The outer loop iterates through rows (i), and the inner loop iterates through columns (j). Inside these loops,scanfreads an integer from the user for each element ofmatrix1andmatrix2. - Perform Addition: Another set of nested
forloops iterates fromi = 0torows - 1andj = 0tocols - 1. In each iteration, the elementmatrix1[i][j]is added tomatrix2[i][j], and the result is stored insumMatrix[i][j]. This performs the element-wise sum. - Display Result: The final set of nested
forloops prints the elements ofsumMatrix. After each row is printed,printf("\n");moves the cursor to the next line, ensuring the output matrix is formatted correctly.
Conclusion
Adding two matrices is a fundamental operation in programming, particularly in numerical computing. By leveraging nested loops and 2D arrays in C, we can efficiently perform element-wise addition, provided the matrices have compatible dimensions. This simple yet powerful technique forms the basis for more complex matrix manipulations and is widely applicable across various scientific and engineering domains.
Summary
- Matrix addition requires two matrices to have identical dimensions (same number of rows and columns).
- Addition is performed element-wise:
C[i][j] = A[i][j] + B[i][j]. - In C, 2D arrays are used to represent matrices.
- Nested
forloops are the primary mechanism to iterate through all elements of the matrices for input, calculation, and output. - The first loop handles rows, and the second (inner) loop handles columns.
- This operation is crucial in fields like image processing, computer graphics, and data analysis.