Home > database >  Recursion C, multiplying two matrix, nothings display
Recursion C, multiplying two matrix, nothings display

Time:12-10

Im passing two matrix from main to function multiply, to multiply two matrix but i dont see any display can anyone guide me, im very new in recursion. (Note its 3 by 3 Matrix already declared)

const r=3;
const c=3;
const row=3;
int multiply(int a[r][c],int b[r][c]);
int display(int arr[][row]);

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    if(r>3){
        printf("R");
        display(mul);
    }
    if(c==3){
        printf("R");
        r  ;
        c=0;
    }
    else{
        c  ;
        mul[r][c]=a[r][c]*b[r][c];
        multiply(a,b);
    }
}
int display(int mul[][row]){
    int i,j;
    printf("Matrix After Multiplication: \n");
    for(i=0;i<row;i  )
    {
        for(j=0;j<row;j  ){
            printf("%d ",mul[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int m_1[3][3]={1,2,3,
                   1,2,3,
                   1,2,3,}, m_2[3][3]={1,2,3,
                             1,2,3,
                             1,2,3,};
    multiply(m_1,m_2);
}

CodePudding user response:

I assume that the code does element wise multiplication of two matrices in a very very convoluted way. Among other horrors the problem is likely here:

multiply(a[r][c],b[r][c]);

It should be:

multiply(a,b);

Otherwise the actual values are passed as pointers to arrays.


EDIT

there are two more issues:

  • add return after display to break recursion
  • move recursive call to multiply() outside of else branch to advance if either row or column is increased.

The updated code is:

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    printf("%d %d\n", r, c);
    if(r>3){
        display(mul);
        return;
    }
    if(c==3){
        r  ;
        c=0;
    }
    else{
        c  ;
        mul[r][c]=a[r][c]*b[r][c];
    }
    multiply(a,b);
}

CodePudding user response:

I can saw at least 4 errors:

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    if(r>3){
        display(mul);
        return; // missing return to stop execution
    }
    if(c==3){
        r  ;
        c=-1; // you have to restart from -1 due to pre increment
    }
    //else should be removed to continue recursion at the end of each row
    {
        c  ;
        mul[r][c]=a[r][c]*b[r][c];
        multiply(a,b);  // you need to pass matrix, not single elements...
    }
}
  •  Tags:  
  • c
  • Related