1// Aim: Program to perform Bankers Algorithm operations (Bankers Algorithm).
2#include<stdio.h>
3#define MAX 10
4
5int main() {
6 int alloc[MAX][MAX], max[MAX][MAX], avail[MAX], need[MAX][MAX];
7 int finish[MAX], safe_seq[MAX];
8 int proc, res, i, j, k, count = 0;
9
10 printf("Enter the number of processes: ");
11 scanf("%d", &proc);
12 printf("Enter the number of resources: ");
13 scanf("%d", &res);
14 printf("Enter the allocation matrix:\n");
15 for (i = 0; i < proc; i++) {
16 for (j = 0; j < res; j++) {
17 scanf("%d", &alloc[i][j]);
18 }
19 }
20 printf("Enter the max matrix:\n");
21 for (i = 0; i < proc; i++) {
22 for (j = 0; j < res; j++) {
23 scanf("%d", &max[i][j]);
24 }
25 }
26 printf("Enter the available resources:\n");
27 for (i = 0; i < res; i++) {
28 scanf("%d", &avail[i]);
29 }
30
31 // Calculate the need matrix
32 for (i = 0; i < proc; i++) {
33 for (j = 0; j < res; j++) {
34 need[i][j] = max[i][j] - alloc[i][j];
35 }
36 }
37
38 // mark all processes as unfinished
39 for (i = 0; i < proc; i++) {
40 finish[i] = 0;
41 }
42 int work[MAX];
43 for (i = 0; i < res; i++) {
44 work[i] = avail[i];
45 }
46
47 while(count < proc) {
48 int found = 0;
49 for (i = 0; i < proc; i++) {
50 if (finish[i] == 0) {
51 int can_allocate = 1;
52 for (j = 0; j < res; j++) {
53 if (need[i][j] > work[j]) {
54 can_allocate = 0;
55 break;
56 }
57 }
58 if (can_allocate) {
59 for (j = 0; j < res; j++) {
60 work[j] += alloc[i][j];
61 }
62 safe_seq[count++] = i;
63 finish[i] = 1;
64 found = 1;
65 }
66 }
67 }
68 if (found == 0) {
69 printf("System is not in a safe state\n");
70 return 0;
71 }
72 }
73 printf("System is in a safe state.\nSafe sequence is: ");
74 for (i = 0; i < proc-1; i++) {
75 printf("%d -> ", safe_seq[i]);
76 }
77 printf("%d\n", safe_seq[proc-1]);
78 return 0;
79}
80
81