Implementation of Priority Scheduling Algorithm in C++

#include<iostream.h>

#include<conio.h>

struct process

{

  int no;

  int at;

  int et;

  int wt;

  int tt;

  int p;

};

void main()

{

  clrscr();

  process p[4];

  int i, j;

  for (i = 0; i < 4; i++)

  {

    cout << "\n Enter execution time of P" << i + 1 << ":";

    cin >> p[i].et;

    cout << "\n Enter Priority P" << i + 1 << ":";

    cin >> p[i].p;

    p[i].no = i;

    p[i].at = 0;

  }

  cout << "\n PNO\tAT\tET";

  for (i = 0; i < 4; i++)

  {

    cout << "\n P" << p[i].no + 1 << "\t" << p[i].at << "\t" << p[i].et;

  }

  //sorting

  process temp;

  for (i = 0; i < 4; i++)

  {

    for (j = i + 1; j < 4; j++)

    {

      if (p[i].p < p[j].p)

      {

        temp = p[i];

        p[i] = p[j];

        p[j] = temp;

      }

    }

  }

  p[0].wt = 0;

  p[0].tt = p[0].et;

  int tte = p[0].et;

  for (i = 1; i < 4; i++)

  {

    p[i].wt = p[i - 1].wt + p[i - 1].et - (p[i].at - p[i - 1].at);

    p[i].tt = p[i].wt + p[i].et;

    tte = tte + p[i].et;

  }

  cout << " \n Result";

  cout << "\n PNO\tAT\tWT\tET\tTT";

  for (i = 0; i < 4; i++)

  {

    cout << "\n P" << p[i].no + 1 << "\t" << p[i].at << "\t" << p[i].wt << "\t" << p[i].et << "\t" << p[i].tt;

  }

  cout << "\n Total time:" << tte;

  int twt = 0, tat = 0;

  for (i = 0; i < 4; i++)

  {

    twt += p[i].wt;

    tat += p[i].tt;

  }

  float awt = (float) twt / 4;

  cout << "\n Average Waiting time:" << awt;

  float atat = (float) tat / 4;

  cout << "\n Average Turnaround Time:" << atat;

  getch();

}

/* Output





 Enter execution time of P1:5



 Enter Priority P1:4



 Enter execution time of P2:3



 Enter Priority P2:1



 Enter execution time of P3:6



 Enter Priority P3:5



 Enter execution time of P4:2



 Enter Priority P4:2



 PNO    AT      ET

 P1     0       5

 P2     0       3

 P3     0       6

 P4     0       2

 Result

 PNO    AT      WT      ET      TT

 P3     0       0       6       6

 P1     0       6       5       11

 P4     0       11      2       13

 P2     0       13      3       16

 Total time:16

 Average Waiting time:7.5

 Average Turnaround Time:11.5



*/

Leave a Reply

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