Implementing First Fit Algorithm in C++

Here is C++ implementation of first fit algorithm.

#include<iostream.h>

#include<conio.h>

struct job

{

  int no;

  int size;

  int add;

};

struct mem

{

  int no;

  int size;

  int f;

  int jno;

};

void main()

{

  clrscr();

  //Getting No Of Blocks

  cout << "\n Enter No of Blocks in memory:";

  int loc;

  cin >> loc;

  //

  int x, y;

  //

  mem m[99], tempm;

  //Getting Size Of Blocks

  for (int i = 0; i < loc; i++)

  {

    cout << "\n Enter Size of block" << i + 1 << ":";

    cin >> m[i].size;

    m[i].no = i + 1;

    m[i].f = 0;

    m[i].jno = 0;

  }

  //Getting Jobs No

  int jobn;

  cout << "\n Enter No of Jobs:";

  cin >> jobn;

  job j[99];

  //Getting Job Size

  for (x = 0; x < jobn; x++)

  {

    cout << "\n Enter size of Job" << x + 1 << ":";

    cin >> y;

    j[x].no = x + 1;

    j[x].size = y;

    j[x].add = 0;

  }

  //Printing IP

  cout << "\nJobNo\tJobSize";

  for (x = 0; x < jobn; x++)

  {

    cout << "\n";

    cout << j[x].no;

    cout << "\t" << j[x].size;

  }

  //Putting Jobs

  for (x = 0; x < jobn; x++)

  {

    for (y = 0; y < loc; y++)

    {

      //check if space is blank

      if ((m[y].f == 0) && (m[y].size >= j[x].size) && (j[x].add != 1))

      {

        m[y].jno = j[x].no;

        m[y].f = 1;

        j[x].add = 1;

      }

    }

  }

  cout << "\nBlockNo\tMemSize\tJobNo\tJobSize\tStatus\tInternalFreg";

  for (x = 0; x < loc; x++)

  {

    cout << "\n";

    cout << m[x].no;

    cout << "\t" << m[x].size;

    cout << "\t" << m[x].jno;

    y = m[x].jno;

    y = y - 1;

    if (m[x].jno != 0)

      cout << "\t" << j[y].size;

    else

      cout << "\t" << "0";

    cout << "\t" << m[x].f;

    if (m[x].jno != 0)

      cout << "\t" << m[x].size - j[y].size;

    else

      cout << "\t" << "0";

  }

  getch();

}

/* Output





 Enter No of Blocks in memory:4



 Enter Size of block1:30



 Enter Size of block2:15



 Enter Size of block3:50



 Enter Size of block4:20



 Enter No of Jobs:4



 Enter size of Job1:10



 Enter size of Job2:20



 Enter size of Job3:30



 Enter size of Job4:10



JobNo   JobSize

1       10

2       20

3       30

4       10

BlockNo MemSize JobNo   JobSize Status  InternalFreg

1       30      1       10      1       20

2       15      4       10      1       5

3       50      2       20      1       30

4       20      0       0       0       0



*/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.