C Program to Implements Matrix Calculation

Below is a simple C program that creates a menu-driven program to implement matrix addition, subtraction, and multiplication. This program assumes that the matrices are square matrices of the same size for addition and subtraction, and suitable for matrix multiplication.

Program :

#include<stdio.h>
#include<conio.h>
 
int sum(int x[100][100], int y[100][100], int result[100][100], int v, int q)
{
int i,j;
for(i=0;i<v;i++)
    for(j=0;j<q;j++)
    result[i][j] = x[i][j] + y[i][j];
}
int sub(int x[100][100], int y[100][100], int result[100][100], int v, int q)
{
int i,j;
for(i=0;i<v;i++)
    for(j=0;j<q;j++)
    result[i][j] = x[i][j] – y[i][j];
}
int mul(int x[100][100], int y[100][100], int result[100][100], int v, int q)
{
int i,j;
for(i=0;i<v;i++)
    for(j=0;j<q;j++)
    result[i][j] = x[i][j] * y[i][j];
}
void display(int matrix[100][100], int v, int q)
{
int i,j;
  for( i=0; i<v; i++)
  {
    for( j=0; j<q; j++)
      printf(“%d\t”,matrix[i][j]);
 
    printf(“\n”);
  }
}
int main()
{
  int r, c, d[100][100], a[100][100], b[100][100], e[100][100], i, j, z, choice;
  printf(“Enter the number of rows (between 1 and 100): “);
  scanf(“%d”, &r);
  printf(“Enter the number of columns (between 1 and 100): “);
  scanf(“%d”, &c);
 
  printf(“\nEnter elements of 1st matrix:\n”);
  for (i = 0; i < r; ++i)
  {
    for (j = 0; j < c; ++j) 
{
      printf(“Enter element a%d%d: “, i + 1, j + 1);
      scanf(“%d”, &a[i][j]);
    }
  }
 
  printf(“Enter elements of 2nd matrix:\n”);
  for (i = 0; i < r; ++i)
  {
    for (j = 0; j < c; ++j) 
{
      printf(“Enter element b%d%d: “, i + 1, j + 1);
      scanf(“%d”, &b[i][j]);
    }
  }
    printf(“\nChoose the matrix operation,\n”);
    printf(“—————————-\n”);
    printf(“1. Addition\n”);
    printf(“2. Subtraction\n”);
    printf(“3. Multiplication\n”);
    printf(“—————————-\n”);
    printf(“Enter your choice: “);
    scanf(“%d”, &choice);
 
    switch (choice) {
      case 1:
        sum(a, b, d, r, c);
        printf(“Sum of matrix: \n”);
        display(d, r, c);
        break;
      case 2:
        sub(a, b, d, r, c);
        printf(“Subtraction of matrix: \n”);
        display(d, r, c);
        break;
      case 3:
        mul(a, b, d, r, c);
        printf(“Multiplication of matrix: \n”);
        display(d, r, c);
        break;
      default:
        printf(“Invalid input.\n”);
        printf(“Please enter the correct input.\n”);
  
}
}

Output :

Leave a Comment

Your email address will not be published.

Shopping Basket
Verified by MonsterInsights