Thursday 26 December 2013

C Program to Multiply two Matrices using Recursion

#include<stdio.h>
#define MAX 10

void matMult(int [MAX][MAX],int [MAX][MAX]);
int r1,r2,c1,c2;
int c[MAX][MAX];

int main(){

    int a[MAX][MAX],b[MAX][MAX],i,j,k;

    printf("Enter the row and column of first matrix: ");
    scanf("%d%d",&r1,&c1);
    printf("Enter the row and column of second matrix: ");
    scanf("%d%d",&r2,&c2);

    if(c1!=o){
         printf("Matrix mutiplication is not possible");
    }
  else{

      printf("Enter the First matrix: ");
      for(i=0;i<r1;i++)
      for(j=0;j<c1;j++)
           scanf("%d",&a[i][j]);

      printf("Enter the Second matrix: ");
      for(i=0;i<r2;i++)
      for(j=0;j<c2;j++)
           scanf("%d",&b[i][j]);

      printf("nThe First matrix is: n");
      for(i=0;i<r1;i++){
      printf("n");
      for(j=0;j<c1;j++){
           printf("%dt",a[i][j]);
      }
      }

      printf("nThe Second matrix is: n");
      for(i=0;i<r2;i++){
      printf("n");
      for(j=0;j<c2;j++){
           printf("%dt",b[i][j]);
      }
      }

      matMult(a,b);

  }

  printf("nThe multiplication of two matrixes is: n");
  for(i=0;i<r1;i++){
      printf("n");
      for(j=0;j<c2;j++){
           printf("%dt",c[i][j]);
      }
  }
  return 0;
}

void matMult(int a[MAX][MAX],int b[MAX][MAX]){

    static int sum,i=0,j=0,k=0;

    if(i<r1) //row of first matrix
    {
      if(j<c2) //column of second matrix
      {
         if(k<c1)
         {
             sum=sum+a[i][k]*b[k][j];
             k++;
             matMult(a,b);
         }
         c[i][j]=sum;
             sum=0;
             k=0;
             j++;
             matMult(a,b);
      }
        j=0;
        i++;
        matMult(a,b);
    }
}
output :

Enter the row and column of first matrix: 2 2
Enter the row and column of second matrix: 2 2
Enter the First matrix: 1 2 3 4
Enter the Second matrix: 1 2 1 2

The First matrix is:

1       2
3       4
The Second matrix is:

1       2
1       2
The multiplication of two matrixes is:

3       6
7       14

No comments:

Post a Comment