Search code examples
c#algorithmdisk

computing of sstf algorithm in console with c#


I am writing a console program for computing the SSTF algorithm in C#. I don't write a SSTF algorithm for disk controller or an operating system. In the last lines where values add to sum, the compiler gives an error about the index variable, so I declared the index variable before the while loop but the compiler still reports an error.

static void Main(string[] args)
{
    List<int> tracks = new List<int>();
    Console.WriteLine(" enter the current track");
    int key = Convert.ToInt32 (Console.ReadLine());

    Console.WriteLine("enter the tracks's number and -1 to end.");
    int track = Convert.ToInt32(Console.ReadLine());
    while(track != -1)
    {  
        tracks.Add(Convert.ToInt32(track));
        track = Convert.ToInt32(Console.ReadLine());
    }
    int sum=0;
    int count_of_tracks = tracks.Count;
    int distance;
    int minmum;
    int first;
    int index;

    while (tracks.Count != 0)
    {
        first = tracks[0];

        if (key > first)
            minmum = key - first;

        else
            minmum = first - key;

        for (int j = 1; j <= count_of_tracks; j++)
        {
            if (key > tracks[j])
            {
                distance = key - tracks[j];

                if (minmum > distance)
                {
                    minmum = distance;
                    index = j;
                }
            }
            if (key < tracks[j])
            {
                distance = tracks[j] - key;

                if (minmum > distance)
                {
                    minmum = distance;
                    index = j;
                }
            }
        }

        sum = sum + (key - tracks[index]);
        tracks.RemoveAt(index);
    }

    int seek_time = sum / count_of_tracks;        
}

Solution

  • There may be a case where index is never assigned a value. To make the compiler happy, assign a default value:

    int index = -1;
    

    If you want to handle it properly you need something like:

    if(index >= 0)
    {
        sum = sum + (key - tracks[index]);
        tracks.RemoveAt(index);
    }
    else
    {
        // Show / log error ...
    }