# SSTF Algorithm Program in C

Before implementing SSTF Algorithm Program in C, let us understand the working of SSTF algorithm. SSTF selects the request with the least seek time from the current head position. SSTF chooses the pending request closest to the current head position.

e.g. for the same question (as in FCFS), the order of request serviced using SSTF will be:
53 -> 65 -> 67 -> 37 -> 14 -> 98 -> 122 -> 124 -> 183
Thus, the total head movement is |65-53|+|67-65|+|37-67|+|14-37|+|98-14|+|122-98|+|124-122|+|183-124| = 12+2+30+23+84+24+2+59 = 236

### Variable Description

req[] – array for taking the request, index[] – array for store the distance of each request from current position, a[] – array to store the final sequence in which requests should be fulfilled, min – to find the nearest request from the index array, mini – stores the index of nearest request, mov – to calculate total head movement, cp1 – to save the initial value of current position

## SSTF Algorithm Program in C

``````#include<math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,k,req,mov=0,cp,index,min,a,j=0,mini,cp1;
printf("enter the current position\n");
scanf("%d",&cp);
printf("enter the number of requests\n");
scanf("%d",&n);
cp1=cp;
printf("enter the request order\n");
for(i=0;i<n;i++)
{
scanf("%d",&req[i]);
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
index[i]=abs(cp-req[i]); // calculate distance of each request from current position
}
// to find the nearest request
min=index;
mini=0;
for(i=1;i<n;i++)
{
if(min>index[i])
{
min=index[i];
mini=i;
}
}
a[j]=req[mini];
j++;
cp=req[mini]; // change the current position value to next request
req[mini]=999;
} // the request that is processed its value is changed so that it is not processed again
printf("Sequence is : ");
printf("%d",cp1);
printf(" -> %d",a);
for(i=1;i<n;i++)
{