FCFS and SJF CPU Scheduling C Program Example
FCFS and SJF CPU Scheduling C Program Example
Corrected and formatted C source code for FCFS and SJF scheduling.
FCFS Scheduling C Implementation
#include <stdio.h>
int FCFS() {
int bt[15], n, i, wt[15];
float twt = 0, tat = 0, att, awt;
printf("\nTHE FCFS SCHEDULING\n");
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter burst time of all the processes:\n");
for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d", &bt[i]);
}
wt[0] = 0;
// for calculating waiting time of each process
for (i = 1; i < n; i++)
wt[i] = bt[i - 1] + wt[i - 1];
printf("ProcessID\tBurstTime\tWaitingTime\tTurn Around Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t\t%d\t\t%d\t\t%d\n", i + 1, bt[i], wt[i], bt[i] + wt[i]);
// calculating total waiting time
twt += wt[i];
// for calculating total turn around time
tat += (wt[i] + bt[i]);
}
// for calculating average waiting time
awt = twt / n;
// for calculating average turn around time
att = tat / n;
printf("\nAvg. waiting time = %f\n", awt);
printf("Avg. turn around time = %f\n", att);
return 0;
}
SJF Scheduling C Implementation
int SJF() {
int bt[20], p[20], wt[20], tat[20], i, j, n, total = 0, pos, temp;
float avg_wt, avg_tat;
printf("\nTHE SJF SCHEDULING\n");
printf("Enter the number of process: ");
scanf("%d", &n);
printf("\nEnter Burst time:\n");
for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d", &bt[i]);
p[i] = i + 1;
}
// sorting of burst times (selection sort)
for (i = 0; i < n; i++) {
pos = i;
for (j = i + 1; j < n; j++) {
if (bt[j] < bt[pos])
pos = j;
}
temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;
temp = p[i];
p[i] = p[pos];
p[pos] = temp;
}
wt[0] = 0;
for (i = 1; i < n; i++) {
wt[i] = 0;
for (j = 0; j < i; j++)
wt[i] += bt[j];
total += wt[i];
}
avg_wt = (float) total / n;
total = 0;
printf("\nProcess\tBurstTime\tWaiting Time\tTurn around time\n");
for (i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
total += tat[i];
printf("P%d\t%d\t\t%d\t\t%d\n", p[i], bt[i], wt[i], tat[i]);
}
avg_tat = (float) total / n;
printf("\n\nAverage Waiting Time = %f", avg_wt);
printf("\nAverage Turnaround Time = %f\n", avg_tat);
return 0;
}
Main Function
int main() {
FCFS();
SJF();
return 0;
}
Notes
- This code implements FCFS and SJF CPU scheduling in C.
- Arrays are sized to support up to 15 or 20 processes where declared.
- Input: number of processes and burst times for each process.
- Outputs include waiting time, turn around time, and averages.
English with a size of 3.03 KB