Write a C program to simulate Non-preemptive Shortest Job First (SJF) – 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 waitingTime; // Waiting Time

    int turnaroundTime; // Turnaround Time

} Process;


// Function to sort processes by burst time (SJF)

void sortByBurstTime(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].burstTime > p[j].burstTime) {

                temp = p[i];

                p[i] = p[j];

                p[j] = temp;

            }

        }

    }

}


// Function to find waiting time and turnaround time

void findWaitingTime(Process p[], int n) {

    int time = 0;

    

    // Sorting processes by arrival time initially

    sortByBurstTime(p, n);


    for (int i = 0; i < n; i++) {

        if (time < p[i].arrivalTime) {

            time = p[i].arrivalTime;

        }

        p[i].waitingTime = time - p[i].arrivalTime;

        time += p[i].burstTime;

        p[i].turnaroundTime = p[i].waitingTime + p[i].burstTime;

    }

}


void findAverageTimes(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);

}


void printProcesses(Process p[], int n) {

    printf("Process 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",

               p[i].id,

               p[i].arrivalTime,

               p[i].burstTime,

               p[i].waitingTime,

               p[i].turnaroundTime);

    }

}


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 and burst time for process %d: ", i + 1);

        p[i].id = i + 1;

        scanf("%d %d", &p[i].arrivalTime, &p[i].burstTime);

    }

    

    // Calculate waiting time and turnaround time

    findWaitingTime(p, n);

    

    // Print process details

    printProcesses(p, n);

    

    // Calculate and print average waiting time and turnaround time

    findAverageTimes(p, n);

    

    return 0;

}