Write the program to simulate Non preemptive priority scheduling. The arrival time and first CPU-burst of different jobs should be input to the system. Accept no. of Processes, arrival time and burst time. The output should give turnaround time and waiting time for each process. Also find the average waiting time and turnaround time.
#include <stdio.h>
#define MAX 100
// Structure to hold process details
typedef struct {
int id; // Process ID
int arrivalTime; // Arrival Time
int burstTime; // Burst Time
int priority; // Priority
int waitingTime; // Waiting Time
int turnaroundTime; // Turnaround Time
} Process;
// Function to sort processes by priority
void sortByPriority(Process p[], int n) {
Process temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (p[i].priority > p[j].priority) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
// Function to calculate waiting time and turnaround time
void calculateTimes(Process p[], int n) {
int time = 0;
int processCompleted = 0;
int isCompleted[MAX] = {0};
while (processCompleted < n) {
int minPriorityIndex = -1;
for (int i = 0; i < n; i++) {
if (!isCompleted[i] && p[i].arrivalTime <= time) {
if (minPriorityIndex == -1 || p[i].priority < p[minPriorityIndex].priority) {
minPriorityIndex = i;
}
}
}
if (minPriorityIndex != -1) {
p[minPriorityIndex].waitingTime = time - p[minPriorityIndex].arrivalTime;
time += p[minPriorityIndex].burstTime;
p[minPriorityIndex].turnaroundTime = p[minPriorityIndex].waitingTime + p[minPriorityIndex].burstTime;
isCompleted[minPriorityIndex] = 1;
processCompleted++;
} else {
time++;
}
}
}
void printProcesses(Process p[], int n) {
printf("Process ID\tArrival Time\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",
p[i].id,
p[i].arrivalTime,
p[i].burstTime,
p[i].priority,
p[i].waitingTime,
p[i].turnaroundTime);
}
}
void calculateAverages(Process p[], int n) {
float totalWaitingTime = 0;
float totalTurnaroundTime = 0;
for (int i = 0; i < n; i++) {
totalWaitingTime += p[i].waitingTime;
totalTurnaroundTime += p[i].turnaroundTime;
}
printf("Average Waiting Time: %.2f\n", totalWaitingTime / n);
printf("Average Turnaround Time: %.2f\n", totalTurnaroundTime / n);
}
int main() {
int n;
Process p[MAX];
printf("Enter number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter arrival time, burst time and priority for process %d: ", i + 1);
p[i].id = i + 1;
scanf("%d %d %d", &p[i].arrivalTime, &p[i].burstTime, &p[i].priority);
}
// Sort processes by priority
sortByPriority(p, n);
// Calculate waiting time and turnaround time
calculateTimes(p, n);
// Print process details
printProcesses(p, n);
// Calculate and print average waiting time and turnaround time
calculateAverages(p, n);
return 0;
}
0 Comments