Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Tuesday 11 September 2018

Bankers Algorithm Implementation

                 C Program to implement Bankers Algorithm




#include<stdio.h>
main()
{
 int max[20],all[20],need[20],seq[20],avail,work,i,j=0,d,m,n,e;
 printf("Enter no of process: ");
 scanf("%d",&n);
 printf("Enter max allocated resources to the process:\n");
 for(i=0;i<n;i++)
 {
  printf("\nmax of p[%d] : ",i);
  scanf("%d",&max[i]);
  printf("\nAllocation of p[%d] : ",i);
  scanf("%d",&all[i]);
  need[i]=max[i]-all[i];
  printf("\nneed of p[%d] : %d",i,need[i]);
 }
 printf("\n\nEnter available resources");
 scanf("%d",&avail);
 printf("\nMax\tallocation\tneed \n");
 for(i=0;i<n;i++)
  printf("%3d\t%3d\t%3d\n",max[i],all[i],need[i]);
 m=d=n;
 e=m+1;
 while(m>0)
 {
  if(d==e)
   m=0;
  else
  {
   d=e;
   e=0;
   for(i=0;i<n;i++)
    if((need[i]>0)&&(need[i]<=avail))
    {
     need[i]=0;
     work=all[i]+avail;
     avail=work;
     seq[j]=i;
     m--;
     j++;
    }
    else
     e++;
  }
 }
 if(d==e)
  printf("\n an unsafe sequence\n");
 else
 {
  printf("\n safe sequence\n");
  printf("\nThe sequence of process is :");
  printf("<");
  for(i=0;i<n;i++)
   printf("p[%d] ",seq[i]);
   printf(">");
 }
}

No comments:

Post a Comment