Thursday 15 December 2016

C program for Matrix Manipulation

To understand two-dimensional(2D) arrays in C, quite often matrix data structure is used. Here is a simple program to learn how matrix is created, adding two matrices, multiplying two matrices and how to display the 2D array in the matrix form.

The program is not efficient since static memory allocation is used which will waste more memory space. But this program will surely help to learn the basics behind 2D arrays and passing 2D arrays to functions.

//Program for matrix manipulation
#include<stdio.h>
#include<conio.h>
main()
{
  int mat1[5][5], mat2[5][5],i,j,m1,n1, m2,n2;

  clrscr();
  printf("Enter the order of matrix 1\n");
  scanf("%d%d",&m1,&n1);
  printf("\n Enter matrix 1\n");
  for(i=0;i<m1;i++)
   for(j=0;j<n1;j++)
    scanf("%d", &mat1[i][j]);

  printf("Enter the order of matrix 2\n");
  scanf("%d%d",&m2,&n2);
  printf("\n Enter matrix 2\n");
  for(i=0;i<m2;i++)
   for(j=0;j<n2;j++)
    scanf("%d",&mat2[i][j]);
 
   printf("Given matrix1\n");
   display(mat1,m1,n1);
 
   printf("Given matrix2\n");
   display(mat2,m2,n2);
 
   add(mat1,mat2,m1,n1,m2,n2);
   multiply(mat1,mat2,m1,n1,m2,n2);
   getch();
}

display(int mat[5][5],int m,int n)
{
  int i,j;

  for(i=0;i<m;i++)
  {
    for(j=0;j<n;j++)
    printf("%d\t",mat[i][j]);
    printf("\n");
  }
}

add(int a[5][5],int b[5][5],int m1,int n1,int m2,int n2)
{
  int i,j;
  int result[5][5];

  if ((m1==m2) && (n1==n2))
  {
    for(i=0;i<m1;i++)
      for(j=0;j<n1;j++)
      result[i][j]=a[i][j] + b[i][j];
    printf("The sum matrix \n");
    display(result,m1,n1);
  }
  else
  printf("The matrices cannot be added because their orders are not same\n");
}

multiply(int a[5][5],int b[5][5],int m1,int n1,int m2,int n2)
{
  int i,j,k;
  int result[5][5];

  if (n1==m2)
  {
    for(i=0;i<m1;i++)
      for(j=0;j<n2;j++)
      {
result[i][j]=0;
for(k=0;k<n1;k++)
  result[i][j]=result[i][j]+a[i][k] * b[k][j];
       }
    printf("The product matrix \n");
    display(result,m1,n1);
  }
  else
  printf("The matrices cannot be multiplied because the number of columns in matrix1 is not equal to the number of rows in matrix2\n");
}

/*
OUTPUT
--------
Enter the order of matrix 1
2 2

Enter matrix 1
1 1 1 1
Enter the order of matrix 2
2 2

Enter matrix 2
3 3 3 3
Given matrix1
1       1
1       1
Given matrix2
3       3
3       3
The sum matrix
4       4
4       4
The product matrix
6       6
6       6
*/

No comments:

Post a Comment