Write a program for matrix operations (Addition, subtraction, and multiplication).
1 . Addition of Two Matrices
C Program
#include <stdio.h>int main(){int matrixA[][3] = {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}};int matrixB[][3] = {{3, 4, 2}, {4, 6, 2}, {3, 2, 5}};int n = 3, m = 3;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){matrixA[i][j] = matrixA[i][j] + matrixB[i][j];}}printf("Addition of matrices is\n");for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){printf("%d ", matrixA[i][j]);}printf("\n");}return 0;}
Output:
Addition of matrices is
4 6 5
7 10 7
8 8 12
2. Subtraction of Two matrices
C Program
#include <stdio.h>int main(){int matrixA[][3] = {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}};int matrixB[][3] = {{3, 4, 2}, {4, 6, 2}, {3, 2, 5}};int n = 3, m = 3;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){matrixA[i][j] = matrixA[i][j] - matrixB[i][j];}}printf("Subtraction of matrices is\n");for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){printf("%d ", matrixA[i][j]);}printf("\n");}return 0;}
Output:
Subtraction of matrices is
-2 -2 1
-1 -2 3
2 4 2
3 . Multiplication of Two matrices
C Program
#include <stdio.h>int main(){int matrixA[][3] = {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}};int matrixB[][3] = {{3, 4, 2}, {4, 6, 2}, {3, 2, 5}};int n = 3;int matrixC[3][3];for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){matrixC[i][j] = 0;for (int k = 0; k < n; k++){matrixC[i][j] = matrixC[i][j] + matrixA[i][k] * matrixB[k][j];}}}printf("Multiplication of matrices is\n");for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){printf("%d ", matrixC[i][j]);}printf("\n");}return 0;}
Output:
Multiplication of matrices is
20 22 21
40 46 39
60 70 57
No comments:
Post a Comment