# Program to solve Stable marriage problem in C.

Given n men and n women, where each person has ranked all members of the opposite sex with a unique number between 1 and n in order of preference, marry the men and women off such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are “stable”.

```#include<stdio.h>

int b[100][100],g[100][100],s[2][100];

main()
{
int n,i,j,k;

FILE *fp;

fp= fopen("prefer.dat","r");

fscanf(fp,"%d",&n);

printf(" the number of couples %d:\n",n);
printf("PREFERENCE OF MALE\n");
for(i=0;i<n;i++)

{
for(j=0;j<n+1;j++)
{
fscanf(fp,"%d",&b[j][i]);
printf("%d\t",b[j][i]);
}
printf("\n");
}
printf("PREFERENCE OF FEMALE\n");
for(i=0;i<n;i++)
{
for(j=0;j<n+1;j++)
{
fscanf(fp,"%d",&g[j][i]);
printf("%d\t",g[j][i]);
}
printf("\n");
}

for(i=0;i<n;i++){
s[0][i]=b[0][i];
s[1][i]=b[1][i];
match(i,n);
}
printf("FINAL OUTPUT\n");
for(i=0;i<n;i++){
printf("%d      %d\n",s[0][i],s[1][i]);
}
}

int match(int i,int n)
{
int j,k,h,t,m;
for(j=0;j<=i;j++)
{
for(m=0;m<=i;m++)
{
if(m!=j&&s[1][m]==s[1][j])
{
k=s[1][j];
for(h=1;h<n;h++)
{
if (g[h][k-1]==j+1)
{
for (t=1;t<n;t++)
if (k==b[t][m])break;
s[1][m]=b[++t][m];
match(i,n);
return;
}
else if(g[h][k-1]==m+1)
{
for (t=1;t<n;t++)
if (k==b[t][j])break;
s[1][j]=b[++t][j];
match(i,n);
return;
}
}

}
}
}return;
}
```

## 7 thoughts on “Program to solve Stable marriage problem in C.”

1. K says:

Hello. Can you define the variables i, j,k,h,t,m and n?

2. venkat bijjam says:

please give me the prefer.dat file

3. venkat bijjam says:

can you explain s[][] and j,k,h,t,m

4. sai says:

code without using files???????/

5. Denis says:

please give me the prefer.dat file

6. Denis says:

please give me the prefer.dat file)

7. Denis says:

error in this fp= fopen(“prefer.dat”,”rf(fp,”%d”,&n); Help)