In: Computer Science
Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define tprocess 4
// create a struct
struct process
{
int Process_no,arrivaltime,bursttime,pr;
};
process proc[50];
bool comp(process A,process B)
{
if(A.arrivaltime == B.arrivaltime)
{
return A.pr<B.pr;
}
else
{
return A.arrivaltime<B.arrivaltime;
}
}
void get_wt_time(int wt[])
{
// service array that contains cumulative burst time
int service[50];
// Initilising elements of the arrays
service[0] = proc[0].arrivaltime;
wt[0]=0;
for(int i=1;i<tprocess;i++)
{
service[i]=proc[i-1].bursttime+service[i-1];
wt[i]=service[i]-proc[i].arrivaltime;
if(wt[i]<0)
{
wt[i]=0;
}
}
}
void get_tat_time(int tat[],int wt[])
{
for(int i=0;i<tprocess;i++)
{
tat[i]=proc[i].bursttime+wt[i];
}
}
void findtime()
{
//Declare array for waiting time and turnaround time
int wt[50],tat[50];
double wavg=0,tavg=0;
// Function call for waiting time array
get_wt_time(wt);
//Function call for turnaround time
get_tat_time(tat,wt);
int stime[50],ctime[50];
stime[0] = proc[0].arrivaltime;
ctime[0]=stime[0]+tat[0];
// calculating starting and ending time
for(int i=1;i<tprocess;i++)
{
stime[i]=ctime[i-1];
ctime[i]=stime[i]+tat[i]-wt[i];
}
cout<<"Process_no\tStart_time\tComplete_time\tTurn_Around_Time\tWaiting_Time"<<endl;
for(int i=0;i<tprocess;i++)
{
wavg += wt[i];
tavg += tat[i];
cout<<proc[i].Process_no<<"\t\t"<<
stime[i]<<"\t\t"<<ctime[i]<<"\t\t"<<
tat[i]<<"\t\t\t"<<wt[i]<<endl;
}
// display the average waiting time and average turn around
time
cout<<"\nAverage waiting time : ";
cout<<wavg/(float)tprocess<<endl;
cout<<"\nAverage turnaround time : ";
cout<<tavg/(float)tprocess<<endl;
}
int main()
{
int arrivaltime[] = { 1, 2, 3, 4 };
int bursttime[] = { 7, 1, 5, 3 };
int priority[] = { 3, 7, 4, 1 };
for(int i=0;i<tprocess;i++)
{
proc[i].arrivaltime=arrivaltime[i];
proc[i].bursttime=bursttime[i];
proc[i].pr=priority[i];
proc[i].Process_no=i+1;
}
//Using sort function
sort(proc,proc+tprocess,comp);
//Calling function findtime
findtime();
return 0;
}
Output:
Thank You!! Hope you like it.
If any doubt comes up, Please let me know.