Write a program using C to implement non-preemptive priority based scheduling algorithm.
Below is the C program that implements a Non-Preemptive Priority-Based Scheduling algorithm. In this algorithm, each process is assigned a priority, and the process with the highest priority (lowest numerical value) is executed first. If two processes have the same priority, they are scheduled based on their arrival order.
#include <stdio.h> struct Process { int id; // Process ID int burst; // Burst time int priority; // Priority int waiting; // Waiting time int turnaround; // Turnaround time }; // Function to calculate waiting and turnaround times void calculateTimes(struct Process processes[], int n) { int total_waiting = 0, total_turnaround = 0; // Calculate waiting time for each process for (int i = 0; i < n; i++) { if (i == 0) { processes[i].waiting = 0; // First process has no waiting time } else { processes[i].waiting = processes[i - 1].waiting + processes[i - 1].burst; } total_waiting += processes[i].waiting; processes[i].turnaround = processes[i].waiting + processes[i].burst; total_turnaround += processes[i].turnaround; } // Print average waiting and turnaround times printf("Average Waiting Time: %.2f\n", (float)total_waiting / n); printf("Average Turnaround Time: %.2f\n", (float)total_turnaround / n); } // Function to sort processes by priority void sortProcesses(struct Process processes[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (processes[i].priority > processes[j].priority) { struct Process temp = processes[i]; processes[i] = processes[j]; processes[j] = temp; } } } } // Function to print process details void printProcessDetails(struct Process processes[], int n) { printf("\nProcess ID\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\n", processes[i].id, processes[i].burst, processes[i].priority, processes[i].waiting, processes[i].turnaround); } } int main() { int n; // Read the number of processes printf("Enter the number of processes: "); scanf("%d", &n); struct Process processes[n]; // Read process burst times and priorities for (int i = 0; i < n; i++) { processes[i].id = i + 1; // Assign Process ID printf("Enter burst time for Process %d: ", i + 1); scanf("%d", &processes[i].burst); printf("Enter priority for Process %d (lower number means higher priority): ", i + 1); scanf("%d", &processes[i].priority); } // Sort processes by priority sortProcesses(processes, n); // Calculate waiting and turnaround times calculateTimes(processes, n); // Print the process details printProcessDetails(processes, n); return 0; }