Matrix Operations in C Language
Write a Matrix Operations program in C to compute addition or subtraction or multiplication of two matrices. Use functions to read, display and add or subtract or multiply the matrices.
Matrix Operations in C Code
#include<stdio.h> #define ROWS 3 #define COLS 3 void readmatrix(int matrix[ROWS][COLS]); void DisplayMatrix(int matrix[ROWS][COLS]); void AddMatrices(int matrix1[ROWS][COLS], int matrix2[ROWS][COLS], int result[ROWS][COLS]); void SubtractMatrices(int matrix1[ROWS][COLS], int matrix2[ROWS][COLS], int result[ROWS][COLS]); void MultiplyMatrices(int matrix1[ROWS][COLS], int matrix2[ROWS][COLS], int result[ROWS][COLS]); void main() { int md[ROWS][COLS], nd[ROWS][COLS]; int rs[ROWS][COLS]; int ch; clrscr(); while(1) { printf(“Please select operation you wish to do\n”); printf(“1. Enter fresh input, new matrices\n”); printf(“2. Add two matrices\n”); printf(“3. Subtract second matrix from first\n”); printf(“4. Multiply first matrix to the second\n”); printf(“5. Exit \n\n”); printf(“Your Choice: “); /* Read user’s choice into activity */ scanf(“%d”, &ch); switch(ch) { case 1: printf(“Please enter first matrix\n”); readmatrix(md); printf(“Please enter second matrix\n”); readmatrix(nd); break; case 2: AddMatrices(md, nd, rs); printf(“The sum of two the matrices is\n”); DisplayMatrix(rs); break; case 3: SubtractMatrices(md, nd, rs); printf(“The difference of the two matrices is\n”); DisplayMatrix(rs); break; case 4: MultiplyMatrices(md, nd, rs); printf(“The product of the two matrices is\n”); DisplayMatrix(rs); break; case 5: exit(0); } } getch(); } void readmatrix(int matrix[ROWS][COLS]) { int i, j; printf(“Please enter a %d * %d matrix\n”, ROWS, COLS); for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { scanf(“%d”, &matrix[i][j]); } } } void DisplayMatrix(int matrix[ROWS][COLS]) { int i, j; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { printf(“%d\t”, matrix[i][j]); } printf(“\n”); } } void AddMatrices(int md[ROWS][COLS], int nd[ROWS][COLS], int rs[ROWS][COLS]) { int i, j; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { rs[i][j] = md[i][j] + nd[i][j]; } } } void SubtractMatrices(int md[ROWS][COLS], int nd[ROWS][COLS], int rs[ROWS][COLS]) { int i, j; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { rs[i][j] = md[i][j] – nd[i][j]; } } } void MultiplyMatrices(int md[ROWS][COLS], int nd[ROWS][COLS], int rs[ROWS][COLS]) { int i, j, k; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { rs[i][j] = 0; for(k = 0; k < COLS; k++) { rs[i][j] = rs[i][j] + (md[i][k] * nd[k][j]); } } } }
Leave a Reply