This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

26 Jan 2013

C PROGRAM TO PERFORM MATRIX MULTIPLICATION

# C PROGRAM FOR PRODUCT OF TWO MATRICES


#include<stdio.h>
#include<conio.h>
void main()
{
  //using 2D-ARRAYS
  int RowSize,ColSize;
  int Matrix1[5][5];
  int Matrix2[5][5];
  int ResultMatrix[5][5];
  int i, j;
  //clrscr();
  printf("\n >>> PROGRAM To PERFORM MULTIPLICATION OF TWO MATRICES <<<\n");
  printf("\n Enter the Size of a Matrix(For Example:3 3) : ");
  scanf("%d %d",&RowSize,&ColSize);

  if (RowSize > 5 || ColSize > 5)   //limiting the size of matrix
  {
    printf(" The Size Of Matrix should Be in Less Than 5 (limiting size of array)");
    printf("\n\n\t Press Enter key to exit....");
    getch();
    return;
   }

   else
   {
     //Initializing all the elements to zero
     for (i = 0; i < RowSize; i++)
     {
        for (j = 0; j < ColSize; j++)
        {
            Matrix1[i][j] = 0;
            Matrix2[i][j] = 0;
         }
      }
      //Reading elements of Matrix1
      printf("\n Enter the elements of Matrix1(%d * %d) \n", RowSize, ColSize);
      for (i = 0; i < RowSize; i++)
      {
        for (j = 0; j < ColSize; j++)
        {
           printf(" Matrix1[%d][%d] : ", i, j);
           scanf("%d",&Matrix1[i][j]);
        }
       }

       //Reading elements of Matrix2
       printf("\n Enter the elements of Matrix2(%d * %d) \n", RowSize, ColSize);
       for (i = 0; i < RowSize; i++)
       {
         for (j = 0; j < ColSize; j++)
         {
           printf(" Matrix2[%d][%d] : ", i, j);
           scanf("%d",&Matrix2[i][j]);
         }
        }

        //calculating ResultMatrix, by Multiplying the elements of Matrix1 and Matrix2
        for (i = 0; i < RowSize; i++)
        {
          for (j = 0; j < ColSize; j++)
          {
            ResultMatrix[i][j] = Matrix1[i][j] * Matrix2[i][j];
          }
        }

        //Printing Result Matrix
        printf("\n\n\t*** Result Matrix  ***\n\n\t");
        for (i = 0; i < RowSize; i++)
        {
           for (j = 0; j < ColSize; j++)
           {
             if (ResultMatrix[i][j] > 0 &&  ResultMatrix[i][j] < 10)
             {
               //prinnting number as 01,02,etc,.
                printf("0%d ",ResultMatrix[i][j] );
             }
             else
             {
               printf("%d ",ResultMatrix[i][j]);
             }

             if (j == ColSize - 1) { printf("\n\t"); }

            }
          }
        }

       printf("\n\n\t Press Enter key to exit....");
       getch();
 }

Output1:

Output2 :


For C# Program :

C# PROGRAM FOR PRODUCT OF MATRICES USING ARRAYS