In my last post we have seen how to write a program to First Come First Serve.Today we shall write a C program for computation of process basing on Shortest Job First.
This process is same as that of first come first serve but the completion of process will depend on burst time of the process. So the process which has last burst time will completes it's execution first and followed by next process which has next least burst time.
The inputs for this program is the list of processes names with their burst times. now we shall declare array proc_name[100] to store process names and burst[100] to store burst times of the processes.
int n,i,j,t,tot=0,wait[100],burst[100];
char process[100],s[10];
float avg;
printf("\nEnter number of processes:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter name of %d process:",i);
scanf("%s",process[i]);
printf("\nEnter burst time of %d process:",i);
scanf("%d",&burst[i]);
}
The above declaration of variables contain which are used for loop controlling and avg is to find the average waiting time of a process.
After declaration and intake of the input variables we need to check the burst times of the process and need to swap the process following the ascending order of the burst times. Here we shall use bubbles sorting technique to swap those process.The code of the swapping is as follows:
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(burst[i]>burst[j])
{
t=burst[i];
burst[i]=burst[j];
burst[j]=t;
strcpy(s,process[i]);
strcpy(process[i],process[j]);
strcpy(process[j],s);
}
}
}
After swapping of the process's we need to find the waiting time of each process by the formula wait[i]=wait[i-1]+burst[i-1]; and we find total waiting time of all the processes by using the for loop as follows:
for(i=2;i<=n;i++)
{
wait[i]=wait[i-1]+burst[i-1];
tot=tot+wait[i];
}
There fore after writing all the code for all sub parts we shall now write program in a completer manner:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,t,tot=0,wait[100],burst[100];
char process[100],s[10];
float avg;
clrscr();
printf("\nEnter number of processes:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter name of %d process:",i);
scanf("%s",process[i]);
printf("\nEnter burst time of %d process:",i);
scanf("%d",&burst[i]);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(burst[i]>burst[j])
{
t=burst[i];
burst[i]=burst[j];
burst[j]=t;
strcpy(s,process[i]);
strcpy(process[i],process[j]);
strcpy(process[j],s);
}
}
}
wait[1]=0;
for(i=2;i<=n;i++)
{
wait[i]=wait[i-1]+burst[i-1];
tot=tot+wait[i];
}
avg=(float)tot/(float)n;
printf("\nTotal waiting time=%d",tot);
printf("\nAverage waiting time=%f",avg);
getch();
}
No comments:
Post a Comment