#include <iostream>
#include <queue>
using namespace std;

struct Process {
    int pid; // process id
    int bt; // burst time
    int art; // arrival time
    int rem_bt; // remaining burst time
};

void roundRobinScheduling(Process proc[], int n, int quantum) {
    queue<Process> q;
    int wt[n], tat[n], total_wt = 0, total_tat = 0, t = 0;
    for(int i = 0; i < n; i++) {
        proc[i].rem_bt = proc[i].bt;
        wt[i] = 0;
        q.push(proc[i]);
    }
    while(!q.empty()) {
        Process p = q.front();
        q.pop();
        if(p.rem_bt <= quantum) {
            t += p.rem_bt;
            p.rem_bt = 0;
            tat[p.pid] = t - p.art;
            wt[p.pid] = tat[p.pid] - proc[p.pid].bt;
        } else {
            t += quantum;
            p.rem_bt -= quantum;
            while(p.pid != q.front().pid && p.rem_bt > 0) {
                q.push(p);
                p = q.front();
                q.pop();
            }
            if(p.rem_bt > 0) {
                q.push(p);
            }
        }
    }
    for(int i = 0; i < n; i++) {
        total_wt += wt[i];
        total_tat += tat[i];
    }
    float avg_wt = (float) total_wt / n;
    float avg_tat = (float) total_tat / n;
    cout << "Average waiting time = " << avg_wt << endl;
    cout << "Average turnaround time = " << avg_tat << endl;
}

int main() {
    int n, quantum;
    cout << "Enter the number of processes: ";
    cin >> n;
    Process proc[n];
    for(int i = 0; i < n; i++) {
        cout << "Enter the burst time and arrival time for process " << i << ": ";
        cin >> proc[i].bt >> proc[i].art;
        proc[i].pid = i;
    }
    cout << "Enter the time quantum: ";
    cin >> quantum;
    roundRobinScheduling(proc, n, quantum);
    return 0;
}
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.