Skip to main content

First Fit Program and Algorithm in C++ || dot clu

First Fit Program and Algorithm in C++ || dot clu


First Fit Algorithm in C and C++

Here you will learn about first fit algorithm in C and C++ with program examples.
There are various memory management schemes in operating system like first fit, best fit and worst fit. In this section we will talk about first fit scheme.

Suggestion:

What is First Fit Memory Management Scheme?

In this scheme we check the blocks in a sequential manner which means we pick the first process then compare it’s size with first block size if it is less than size of block it is allocated otherwise we move to second block and so on.

First Fit Algorithm

  1. Get no. of Processes and no. of blocks.
  2. After that get the size of each block and process requests.
  3. Now allocate processes
    if(block size >= process size)
    //allocate the process
    else
    //move on to next block
  4. Display the processes with the blocks that are allocated to a respective process.
  5. Stop.
Source code:


  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;
  8.  
  9.     for(i = 0; i < 10; i++)
  10.     {
  11.         flags[i] = 0;
  12.         allocation[i] = -1;
  13.     }
  14.     
  15.     cout<<"Enter no. of blocks: ";
  16.     cin>>bno;
  17.     
  18.     cout<<"\nEnter size of each block: ";
  19.     for(i = 0; i < bno; i++)
  20.         cin>>bsize[i];
  21.  
  22.     cout<<"\nEnter no. of processes: ";
  23.     cin>>pno;
  24.     
  25.     cout<<"\nEnter size of each process: ";
  26.     for(i = 0; i < pno; i++)
  27.         cin>>psize[i];
  28.     for(i = 0; i < pno; i++)         //allocation as per first fit
  29.         for(j = 0; j < bno; j++)
  30.             if(flags[j] == 0 && bsize[j] >= psize[i])
  31.             {
  32.                 allocation[j] = i;
  33.                 flags[j] = 1;
  34.                 break;
  35.             }
  36.     
  37.     //display allocation details
  38.     cout<<"\nBlock no.\tsize\t\tprocess no.\t\tsize";
  39.     for(i = 0; i < bno; i++)
  40.     {
  41.         cout<<"\n"<< i+1<<"\t\t"<<bsize[i]<<"\t\t";
  42.         if(flags[i] == 1)
  43.             cout<<allocation[i]+1<<"\t\t\t"<<psize[allocation[i]];
  44.         else
  45.             cout<<"Not allocated";
  46.     }
  47.     
  48.     return 0;
  49. }

Comments