Advertisement
JavierGumin

CPU Scheduling - SJF

Jun 4th, 2025
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<malloc.h>
  3.  
  4. void main()
  5. {
  6.     int n, i, j, pos, temp, *bt, *wt, *tat, *p;
  7.     float avgwt = 0, avgtat = 0;
  8.     printf("\n Enter the number of processes : ");
  9.     scanf("%d", &n);
  10.  
  11.     p = (int*)malloc(n*sizeof(int));
  12.     bt = (int*)malloc(n*sizeof(int));
  13.     wt = (int*)malloc(n*sizeof(int));
  14.     tat = (int*)malloc(n*sizeof(int));
  15.    
  16.     printf("\n Enter the burst time for each process \n");
  17.     for(i=0; i<n; i++)
  18.     {
  19.         printf(" Burst time for P%d : ", i);
  20.         scanf("%d", &bt[i]);
  21.         p[i] = i;
  22.     }
  23.  
  24.     for(i=0; i<n; i++)
  25.     {
  26.         pos = i;
  27.         for(j=i+1; j<n; j++)
  28.         {
  29.             if(bt[j] < bt[pos])
  30.             {
  31.                 pos = j;
  32.             }
  33.         }
  34.         temp = bt[i];
  35.         bt[i] = bt[pos];
  36.         bt[pos] = temp;
  37.  
  38.         temp = p[i];
  39.         p[i] = p[pos];
  40.         p[pos] = temp;
  41.     }
  42.  
  43.     wt[0] = 0;
  44.     tat[0] = bt[0];
  45.     for(i=1; i<n; i++)
  46.     {
  47.         wt[i] = wt[i-1] + bt[i-1];  //waiting time[p] = waiting time[p-1] + Burst Time[p-1]
  48.         tat[i] = wt[i] + bt[i];     //Turnaround Time = Waiting Time + Burst Time
  49.     }
  50.  
  51.     for(i=0; i<n; i++)
  52.     {
  53.         avgwt += wt[i];
  54.         avgtat += tat[i];
  55.     }
  56.     avgwt = avgwt/n;
  57.     avgtat = avgtat/n;
  58.  
  59.     printf("\n PROCESS \t BURST TIME \t WAITING TIME \t TURNAROUND TIME \n");
  60.     printf("--------------------------------------------------------------\n");
  61.     for(i=0; i<n; i++)
  62.     {
  63.         printf(" P%d \t\t %d \t\t %d \t\t %d \n", p[i], bt[i], wt[i], tat[i]);
  64.     }
  65.  
  66.     printf("\n Average Waiting Time = %f \n Average Turnaround Time = %f \n", avgwt, avgtat);
  67.  
  68.     printf("\n GAANT CHART \n");
  69.     printf("---------------\n");
  70.     for(i=0; i<n; i++)
  71.     {
  72.         printf(" %d\t|| P%d ||\t%d\n", wt[i], p[i], tat[i]);
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement