Want to print combinations of elements of matrix in c

I have a 2d matrix like

1 2 3
4 5 6
7 8 9

and I want to print combinations of first row with rest rows like

1,4,7
1,4,8
1,4,9
1,5,7
1,5,8
1,5,9
..
..
..
2,4,7
...

Rules:
– Every combination starts from top of matrix and proceeds towards bottom. It may switch columns though.
– Every combination should have number of elements equal to number of rows.
– A combination can’t have an element from the same row present twice.
– Number of columns and rows could vary. So solution has to be generic.

Here’s what I have tried:

Since solution needs to be generic, i m priniting the loops and numbers using recursion.

#include<stdio.h>
        int i,n,j,k,row=3,col=3,mat[10][10]={{1,2,3},{4,5,6},{7,8,9}};
        int printnumbers(int n,int i)
        {
                if(n>=row)
                {
                    n=0;
                    printf("n");
                    return 0;
                }
                printf("%d",mat[n][i]);
                printnumbers(n+1,i);
        }
        int printloop(int row,int col)
        {
            //to check whether the function is being called first time. 
            if(row<=0)
                return 0;

            for(i=0;i<col;i++)
            {
                printloop(row-1,col);
                printnumbers(n,i);
            }        
        }
int main()
{

        n=0;
        printloop(row,col);
}

But I m not able to come up with proper printing as desired, not able to think in depth for proper recursion.
The output of this code is:

147
258
369

Source: New Questions

Leave a Reply