FCFS scheduling algorithm in C (Operating Systems)

FCFS scheduling algorithm in C. 

Its working code with output

If you want explanation, you can view my YouTube video. 

Youtube Link


        
#include <stdio.h>
#include <stdlib.h>

typedef struct process
{
  int id, at, bt, wt, tat, ct;
} process;

void sort(process pro[], int n)
{
  process temp;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n - i - 1; j++)
      if (pro[j].at > pro[j + 1].at)
      {
        temp = pro[j];
        pro[j] = pro[j+1];
        pro[j+1] = temp;
      }
}

void display(process pro[], int n)
{
  printf("\n");
  for (int i = 0; i < n; i++)
    printf("P%d AT: %d BT: %d CT: %d TAT: %d WT: %d\n",
           pro[i].id,
           pro[i].at,
           pro[i].bt,
           pro[i].ct,
           pro[i].tat,
           pro[i].wt);
}

void fcfsScheduling(process pro[], int n)
{
  sort(pro, n);
  pro[0].ct = pro[0].bt + pro[0].at;
  pro[0].tat = pro[0].ct - pro[0].at;
  pro[0].wt = pro[0].tat - pro[0].bt;

  int time = pro[0].ct;

  int sumw = 0, sumt = 0;

  for (int i = 1; i < n; i++)
  {
    time += pro[i].bt;
    pro[i].ct = time;
    pro[i].tat = pro[i].ct - pro[i].at;
    pro[i].wt = pro[i].tat - pro[i].bt;
    sumw += pro[i].wt;
    sumt += pro[i].tat;
  }

  display(pro, n);

  printf("\nAvg wating time: %f\nAvg turn around time: %f\n", (sumw * 1.0) / n, (sumt * 1.0) / n);
}

int main()
{
  int n;
  printf("Enter the number of processes: ");
  scanf(" %d", &n);
  struct process pro[n];

  for (int i = 0; i < n; i++)
  {
    pro[i].id = i + 1;
    printf("Arrival time for P%d: ", pro[i].id);
    scanf(" %d", &pro[i].at);

    printf("Burst time for P%d: ", pro[i].id);
    scanf(" %d", &pro[i].bt);
    
    pro[i].wt = pro[i].tat = pro[i].ct = 0;
    printf("\n");
  }

  printf("FCFS Scheduling:\n");
  fcfsScheduling(pro, n);
  return 0;
}
        
    

Comments

Popular posts from this blog

Least Recently Used (LRU) page algorithm in c

Optimal Page Replacement (OPT) in C

LFU Page Replacement Algorithm in C