Write a program using C to implement First-Come, First-Served (FCFS) scheduling algorithm.
Below is the C program that implements the First-Come, First-Served (FCFS) scheduling algorithm for process scheduling. In this program, processes are taken in the order they arrive, and their waiting times and turnaround times are calculated.
#include <stdio.h>
struct Process {
int id; // Process ID
int arrival; // Arrival time
int burst; // Burst time
int waiting; // Waiting time
int turnaround; // Turnaround time
};
void calculateTimes(struct Process processes[], int n) {
int total_waiting = 0;
int total_turnaround = 0;
// Calculate waiting time and turnaround time
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;
}
processes[i].turnaround = processes[i].waiting + processes[i].burst;
total_waiting += processes[i].waiting;
total_turnaround += processes[i].turnaround;
}
// Display the average waiting and turnaround times
printf("\nAverage Waiting Time: %.2f\n", (float)total_waiting / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround / n);
}
void printProcessDetails(struct Process processes[], int n) {
printf("\nProcess ID\tArrival Time\tBurst Time\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].arrival, processes[i].burst,
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 details
for (int i = 0; i < n; i++) {
processes[i].id = i + 1; // Process ID
printf("Enter arrival time and burst time for Process %d: ", i + 1);
scanf("%d %d", &processes[i].arrival, &processes[i].burst);
}
// Sort processes by arrival time (FCFS)
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (processes[i].arrival > processes[j].arrival) {
struct Process temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
// Calculate waiting and turnaround times
calculateTimes(processes, n);
// Print the process details
printProcessDetails(processes, n);
return 0;
}