Program to Implement Banker’s Algorithm
Name Suraj Kumar
Registration No 24157154049
Branch CSE (AI & ML)
Semester 3rd Semester
Aim: To implement Banker’s Algorithm and determine whether the system is in a safe state or
unsafe state.
Algorithm Steps:
1. Input number of processes and resource types.
2. Input Allocation Matrix and Maximum Matrix.
3. Input Available Resources.
4. Calculate Need Matrix using Need = Max − Allocation.
5. Check if Need ≤ Available for any process.
6. If true, allocate resources and update Available.
7. Add process to Safe Sequence.
8. Repeat until all processes finish.
9. If all processes finish → SAFE STATE otherwise → UNSAFE STATE.
Program:
C Program:
#include
int main() {
int n,m,i,j,k;
printf("Enter number of processes: ");
scanf("%d",&n;);
printf("Enter number of resource types: ");
scanf("%d",&m;);
int alloc[n][m], max[n][m], need[n][m], avail[m];
int finish[n], safe[n];
printf("Enter Allocation Matrix:\n");
for(i=0;i for(j=0;j scanf("%d",&alloc;[i][j]);
printf("Enter Maximum Matrix:\n");
for(i=0;i for(j=0;j scanf("%d",&max;[i][j]);
printf("Enter Available Resources:\n");
for(i=0;i scanf("%d",&avail;[i]);
for(i=0;i for(j=0;j need[i][j]=max[i][j]-alloc[i][j];
for(i=0;i finish[i]=0;
int count=0;
while(count int found=0;
for(i=0;i if(!finish[i]){
for(j=0;j if(need[i][j]>avail[j])
break;
if(j==m){
for(k=0;k avail[k]+=alloc[i][k];
safe[count++]=i;
finish[i]=1;
found=1;
}
}
}
if(!found){
printf("System is in Unsafe State");
return 0;
}
}
printf("System is in Safe State\nSafe Sequence: ");
for(i=0;i printf("P%d ",safe[i]);
}