In the following code for optimal page replacement algorithm, the scanf under first for loop is not stopping at the value of 'n' if i enter integer inputs. It works perfectly if the input is repetitive.
EX: If the value of n is 7, and page in put is 1 1 1 1 1 1 1 The code works fine But if the page input is 1 2 3 4 3 2 1 it never stops taking input.
I have even tried explicit declaration in the for loop like i<7 but it still doesn't work Here is my code:
#include<stdio.h>
#include<stdlib.h>
static int MAX =999;
//to find out maximum
int maxim(int a[], int size)
{
if(size <= 0) return -1;
int i, max_i = 0;
int max = a[0];
for(i = 1; i < size; ++i)
{
if(a[i] > max)
{
max = a[i];
max_i = i;
}
}
return max_i;
}
int main()
{
int i,j,k,n,temp_i=0,maximum,temp_j,
count=0,l,pageFault,
page[100],frame[50],position[50];
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("\nEnter the number of frames\n");
scanf("%d",&k);
printf("\nEnter the page sequence\n");
//The problem is in the following two line
for(i=0;i<n;i++)
scanf("%d",&page[i]);
for(i=0;i<k;i++)
frame[i]=-1;
i=0;
while(i<k)
{
frame[i]=page[i];
i++;
count+=1;
}
for(i=k;i<n;i++)
{
for(j=0;j<k;j++)
{
if(frame[j]==page[i])
break;
}
if(j==k)
{
temp_i=i;temp_j=0;
for(l=0;l<k;l++)
position[l]=MAX;
while(temp_i<n)
{
while(temp_j<k)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
temp_j++;
}
//temp_i++;
}
temp_i++;
}
maximum=maxim(position,k);
frame[maximum]=page[i];
count+=1;
}
}
printf("\nThe final frames status is:\n");
for(i=0;i<k;i++)
printf("%d",frame[i]);
pageFault=count;
printf("The number of page fault is %d\n", pageFault);
printf("The hit ratio is %lf\n",(float)pageFault/n);
}