How to add matrix in C
0 212
Adding matrices in C involves combining corresponding elements from two matrices to create a new matrix.
Steps for adding two matrices in C
= =Initialize Matrices: Declare two matrices, each with the same dimensions (number of rows and columns).
Input Matrix Elements: Input the elements of both matrices. You can either hardcode the values or take user input.
Iterate Through Elements: Use nested loops to iterate over each element of the matrices.
Add Corresponding Elements: For each element at position (i, j), add the corresponding elements from both matrices (mat1 and mat2) and store the result in the corresponding position of the resultant matrix (result).
Display the Result: Print the resultant matrix to display the sum of the two input matrices.
Square Matrices Example:
// Program for adding matrix using square matrices #include<stdio.h>#define N 4 void add(int A[][N], int B[][N], int C[][N]) { for (int Q = 0; Q < N; Q++) for (int R = 0; R < N; R++) C[Q][R] = A[Q][R] + B[Q][R]; } void printMatrix(int D[][N]) { for (int Q = 0; Q < N; Q++) { for (int R = 0; R < N; R++) printf("%d ", D[Q][R]); printf("\n"); } } int main() { int A[N][N] = {{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = {{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; printf("Matrix A:\n"); printMatrix(A); printf("Matrix B:\n"); printMatrix(B); add(A, B, C); printf("Result Matrix:\n"); printMatrix(C); return 0; }
Output:
Matrix A: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 Matrix B: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 Result Matrix: 2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8
Rectangular Matrices:
// prgoram for Rectangular Matrices #include<stdio.h>#define M 4 #define N 3 void add(int A[M][N], int B[M][N], int C[M][N]) { for (int Q = 0; Q < M; Q++) for (int R = 0; R < N; R++) C[Q][R] = A[Q][R] + B[Q][R]; } void printMatrix(int D[M][N]) { for (int Q = 0; Q < M; Q++) { for (int R = 0; R < N; R++) printf("%d ", D[Q][R]); printf("\n"); } } int main() { int A[M][N] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4}}; int B[M][N] = {{2, 1, 1}, {1, 2, 2}, {2, 3, 3}, {3, 4, 4}}; int C[M][N]; printf("Matrix A:\n"); printMatrix(A); printf("Matrix B:\n"); printMatrix(B); add(A, B, C); printf("Result Matrix:\n"); printMatrix(C); return 0; }
Output:
Matrix A: 1 1 1 2 2 2 3 3 3 4 4 4 Matrix B: 2 1 1 1 2 2 2 3 3 3 4 4 Result Matrix: 3 2 2 3 4 4 5 6 6 7 8 8
Share:
Comments
Waiting for your comments