Header Ads Widget

Ticker

6/recent/ticker-posts

Write a C program to simulate FCFS CPU scheduling algorithm.

 

#include <stdio.h>


int main() {
    int n, i, j;
    float avg_waiting_time = 0, avg_turnaround_time = 0;
    printf("Enter the number of processes: ");
    scanf("%d", &n);

    int burst_time[n], waiting_time[n], turnaround_time[n];

    printf("Enter burst time for each process: ");
    for (i = 0; i < n; i++) {
        scanf("%d", &burst_time[i]);
    }

    waiting_time[0] = 0;  // Waiting time for first process is zero

    // Calculate waiting time for each process
    for (i = 1; i < n; i++) {
        waiting_time[i] = 0;
        for (j = 0; j < i; j++) {
            waiting_time[i] += burst_time[j];
        }
    }

    // Calculate turnaround time for each process
    for (i = 0; i < n; i++) {
        turnaround_time[i] = burst_time[i] + waiting_time[i];
    }

    // Calculate average waiting time and average turnaround time
    for (i = 0; i < n; i++) {
        avg_waiting_time += waiting_time[i];
        avg_turnaround_time += turnaround_time[i];
    }
    avg_waiting_time /= n;
    avg_turnaround_time /= n;

    // Display the results
    printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
    for (i = 0; i < n; i++) {
        printf("%d\t%d\t\t%d\t\t%d\n", i+1, burst_time[i], waiting_time[i], turnaround_time[i]);
    }
    printf("\nAverage Waiting Time: %.2f", avg_waiting_time);
    printf("\nAverage Turnaround Time: %.2f", avg_turnaround_time);

    return 0;
}
Explanation: The program starts by asking the user to enter the number of processes and burst time for each process. The waiting time and turnaround time arrays are initialized to zero. The waiting time for the first process is set to zero. The waiting time for each subsequent process is calculated as the sum of burst times of all previous processes. The turnaround time for each process is calculated as the sum of its burst time and waiting time. The average waiting time and average turnaround time are calculated by summing up the respective arrays and dividing by the number of processes. Finally, the results are displayed in tabular format along with the average waiting time and average turnaround time.

Post a Comment

0 Comments